2015-06-21 131 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