2015-06-21 128 views
1

我有這種格式如何解析XML文件

<?xml version="1.0" encoding="UTF-8"?> 
<AMG> 
    <Include File="..."/> <!-- comment --> 
    <Include File="...."/> <!-- comment --> 

    <AMGmers Name="Auto"> 
     <Array Type="move" Name="move_name"/> 
    </AMGmers> 

    <AMGmers Name="Black" Parent="Auto"> 
     <Attr Type="Color" Name="auto_Params"/> 
    </AMGmers> 
     <!-- comment --> 

</AMG> 

我不得不從<AMGmers>得到所有名的文件,我要查詢父。 我試圖這樣做

XmlDocument doc1 = new XmlDocument(); 
doc1.Load("test.xml"); 
XmlNodeList elemList1 = doc1.GetElementsByTagName("Name"); 

請幫我理解。

+0

你想得到'Aut o'和'黑色'?或'move_name'和'auto_Params'? – ekad

回答

3

由於<AMG>爲根節點和<AMGmers>標籤內<AMG>,您可以使用此語法

XmlNodeList elemList1 = doc1.SelectNodes("AMG/AMGmers"); 

我假設你想從所有<AMGmers>代碼,並檢查得到Name屬性的值獲得所有<AMGmers>標籤各<AMGmers>標籤是否有Parent屬性,因此該代碼應工作

foreach (XmlNode node in elemList1) 
{ 
    if (node.Attributes["Name"] != null) 
    { 
     string name = node.Attributes["Name"].Value; 

     // do whatever you want with name 
    } 

    if (node.Attributes["Parent"] != null) 
    { 
     // logic when Parent attribute is present 
     // node.Attributes["Parent"].Value is the value of Parent attribute 
    } 
    else 
    { 
     // logic when Parent attribute isn't present 
    } 
} 

編輯

如果你想進去<AMGmers><Array>節點,你可以這樣做如下

foreach (XmlNode node in elemList1) 
{ 
    XmlNodeList arrayNodes = node.SelectNodes("Array"); 
    foreach (XmlNode arrayNode in arrayNodes) 
    { 
     if (arrayNode.Attributes["Type"] != null) 
     { 
      // logic when Type attribute is present 
      // arrayNode.Attributes["Type"].Value is the value of Type attribute 
     } 
    } 
} 

EDIT 2

如果要列舉裏面<AMGmers>的所有節點,你可以這樣做如下

foreach (XmlNode node in elemList1) 
{ 
    foreach (XmlNode childNode in node.ChildNodes) 
    { 
     // do whatever you want with childNode 
    } 
} 
+0

非常感謝,一切正常,請告訴我如何從獲取具體數據到 XmaksasX

+0

具體數據究竟是什麼?你能給個例子嗎? – ekad

+0

此數據 XmaksasX