我想读一些XML文件的值。我能够读取一些值,但我想获取<tools></tools>
- 标签之间的信息。
XmlNodeList xnList = xml.SelectNodes("/instructions/Steps");
foreach (XmlNode xn in xnList)
{
XmlNodeList xnChildList = xn.ChildNodes;
foreach (XmlNode xnc in xnChildList)
{
MessageBox.Show("ID: " + xnc["ID"].InnerText + "Desc: " + xnc["desc"].InnerText);
//this one is working so far!
//I tried to create a new XMLNodeList
XmlNodeList testNodeList = xnc.SelectNodes("/tools");
foreach (XmlNode node in testNodeList)
{
MessageBox.Show(node["tool"].InnerXml);
}
}
}
但它没有用。我该如何处理工具部分?
XML文件如下所示:
<instructions>
<Steps QualificationID="12,3">
<Step>
<ID>1.1</ID>
<desc>desc</desc>
<tools>
<tool ID = "1" name = "10Zoll Steckschl" />
<tool ID = "2" name = "5Zoll Steckschl" />
</tools>
</Step>
<Step>
<ID>1.2</ID>
<desc>desc2</desc>
<tools>
<tool ID = "3" name = "11Zoll Steckschl" />
<tool ID = "4" name = "54Zoll Steckschl" />
</tools>
</Step>
</Steps>
<Steps QualificationID="1223,3">
<Step>
<ID>2.1</ID>
<desc>desc3</desc>
<tools>
<tool ID = "5" name = "14Zoll Steckschl" />
<tool ID = "6" name = "2Zoll Steckschl" />
</tools>
</Step>
<Step>
<ID>2.2</ID>
<desc>desc4</desc>
<tools>
<tool ID = "7" name = "13Zoll Steckschl" />
<tool ID = "8" name = "4Zoll Steckschl" />
</tools>
</Step>
</Steps>
</instructions>
答案 0 :(得分:1)
我强烈怀疑这就是问题所在:
XmlNodeList testNodeList = xnc.SelectNodes("/tools");
前导斜杠将其恢复到根节点 - 您只想在 tools
下查找xnc
元素:
XmlNodeList testNodeList = xnc.SelectNodes("tools");
这就是为什么我个人更喜欢使用LINQ to XML:)
XDocument doc = ...;
foreach (var step in doc.Root.Elements("Steps").Elements("Step"))
{
MessageBox.Show(string.Format("ID: {0} Desc: {1}",
step.Element("ID").Value, step.Element("desc").Value);
foreach (var tool in step.Elements("tools"))
{
...
}
}