繁体   English   中英

如何解析XML文件

[英]how to parsing XML file

我有那种格式的文件

<?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>获得所有名称,并且必须检查可用性Parent。 我试图这样做

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

请帮助我理解。

由于<AMG>是根节点,并且<AMGmers>标记位于<AMG> ,因此您可以使用以下语法获取所有<AMGmers>标记

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

我假设您想从所有<AMGmers>标记中获取Name属性的值,并检查每个<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
        }
    }
}

编辑2

如果要枚举<AMGmers>内的所有节点,则可以如下所示

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM