【发布时间】:2017-01-23 10:32:07
【问题描述】:
以下是我的 XML 文件示例
<?xml version="1.0" encoding="UTF-8"?>
<summary>
<testresult>
<result value="10" name="long">100</result>
<result value="12" name="short">200</result>
<result value="14" name="long">300</result>
</testresult>
<testresult>
<result value="10" name="short">50</result>
<result value="12" name="short">60</result>
<result value="14" name="long">70</result>
</testresult>
</summary>
我需要获取结果元素的属性值。
我使用 foreach 循环完成了它,如下所示。
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(item.Value);
XmlNodeList nodelist = xmlDoc.SelectNodes("//testresult");
for (int i = 0; i < nodelist.Count; i++)
{
foreach (XmlElement child in nodelist[i])
{
if (child.HasAttributes)
{
result.Add(child.Attributes["value"].Value); //This is working fine.
}
}
}
我的最终目标是在 name = "long" only 的情况下识别名称并获得价值。
为此,我需要获取 name Attribute 的值。 我需要这样做不使用 foreach 循环。有什么建议可以在 for 循环中完成我的任务?
谢谢。
【问题讨论】:
-
你必须使用
XmlDocument或者你可以使用LINQ to XML? -
您尝试过使用 XPath 吗? stackoverflow.com/questions/9511608/…
-
@WoutervanVegchel 使用 XPath 您将无法选择属性
标签: c# xml xmldocument