[英]how to parsing XML file
I have a file in that format 我有那种格式的文件
<?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>
I have to get all name from <AMGmers>
, and I have to check availability Parent. 我必须从<AMGmers>
获得所有名称,并且必须检查可用性Parent。 I was trying to do so 我试图这样做
XmlDocument doc1 = new XmlDocument();
doc1.Load("test.xml");
XmlNodeList elemList1 = doc1.GetElementsByTagName("Name");
Please help me understand. 请帮助我理解。
Since <AMG>
is the root node and <AMGmers>
tags are inside <AMG>
, you can get all <AMGmers>
tags using this syntax 由于<AMG>
是根节点,并且<AMGmers>
标记位于<AMG>
,因此您可以使用以下语法获取所有<AMGmers>
标记
XmlNodeList elemList1 = doc1.SelectNodes("AMG/AMGmers");
I assume you want to get the value of Name
attribute from all <AMGmers>
tags and check whether each <AMGmers>
tag has Parent
attribute, so this code should work 我假设您想从所有<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
}
}
EDIT 编辑
If you want to get the <Array>
nodes inside <AMGmers>
, you can do so as below 如果要获取<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 编辑2
If you want to enumerate all nodes inside <AMGmers>
, you can do so as below 如果要枚举<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.