2011-10-31 112 views
0

我想從xml文件中動態讀取xml元素(我的意思是沒有硬編碼元素名稱)。我無法使用XmlReader.ReadToDescendant方法,因爲它需要一個本地名稱,在我的情況下,這個名稱會有所不同。例如,在這種情況下,我需要閱讀元素A,B,C,d &等等使用c#讀取xml文件中的動態元素`

<?xml version="1.0" encoding="UTF-8"?> 
<test Version="2010" xmlns="http://test.org/2010/values"> 
<A> 
    <Data> 
    <Somedata></Somedata> 
    </Data> 
    <Rows> 
     <Row></Row> 
     <Row></Row> 
    </Rows> 
</A> 
<B> 
    <Data> 
    <Somedata></Somedata> 
    </Data> 
    <Rows> 
     <Row></Row> 
     <Row></Row> 
    </Rows> 
</B> 
<C> 
    <Data> 
    <Somedata></Somedata> 
    </Data> 
    <Rows> 
     <Row></Row> 
     <Row></Row> 
    </Rows> 
</C> 
<D> 
    <Data> 
    <Somedata></Somedata> 
    </Data> 
    <Rows> 
     <Row></Row> 
     <Row></Row> 
    </Rows> 
</D> 
</test> 

請幫助我。

+0

你去哪兒得到的名字讀,然後?從另一個文件或數據庫? –

+0

@MarkW:僅限於xml文件。 – user972255

回答

5

這是相當簡單:

XDocument doc = XDocument.Load("test.xml"); 
string name = GetNameFromWherever(); 
foreach (XElement match in doc.Descendants(name)) 
{ 
    ... 
} 

這是使用LINQ to XML - 一個可愛的API爲XML如果你使用.NET 3.5或更高版本......這比使用XmlReader更好

+0

感謝您的回覆。如果我不知道元素,有什麼辦法可以從XmlDocument動態獲取數據嗎? – user972255

+0

@ user972255:目前還不清楚你的意思 - 這是基於可以在執行時獲取的名字來獲取元素,例如,通過詢問用戶。 –

+0

好的。如果你有多個名字,那麼我們需要在子孫循環之上有另一個循環來逐個獲取名字? – user972255

0

對於動態生成的XML內容轉換成另一組類,你可以做這樣的事情:

class GenericNode 
{ 
    private List<GenericNode> _Nodes = new List<GenericNode>(); 
    private List<GenericKeyValue> _Attributes = new List<GenericKeyValue>(); 
    public GenericNode(XElement Element) 
    { 
    this.Name = Element.Name; 
    this._Nodes.AddRange(Element.Elements() 
           .Select(e => New GenericNode(e)); 
    this._Attributes.AddRange(
       Element.Attributes() 
         .Select(a => New GenericKeyValue(a.Key, a.Value)) 
    } 

    public string Name { get; private set; } 
    public IEnumerable<GenericNode> Nodes 
    { 
    get 
    { 
     return this._Nodes; 
    }  
    } 
    public IEnumerable<GenericKeyValue> Attributes 
    { 
    get 
    { 
     return this._Attributes; 
    } 
    } 
} 

class GenericKeyValue 
{ 
    public GenericKeyValue(string Key, string Value) 
    { 
    this.Key = Key; 
    this.Value = Value; 
    } 
    public string Key { get; set; } 
    public string Value { get; set; } 
} 

那你乾脆:

XElement rootElement = XElement.Parse(StringOfXml); // or 
XElement rootElement = XElement.Load(FileOfXml); 

GenericNode rootNode = new GenericRode(rootElement);