我有以下XML文件:
<ChangeInfo >
<Overview name="UML1" >
<Property name="actor1" value="1" />
<Overview name="UML2" >
<Property name="actor2" value="2" />
</Overview>
</Overview>
</ChangeInfo>
我尝试了以下C#代码来访问主节点内的所有嵌套节点:
我想访问<Overview name="UML2">
及其子女。
我的代码:
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Users\Administrator\Downloads\xxml\xxml\xml_file\uml.xml");
XmlNode targets = doc.SelectSingleNode("/ChangeInfo/Overview");
IEnumerator s = targetlist.GetEnumerator();
while (s.MoveNext())
{
XmlNode x = (XmlNode)(s.Current);
XmlNodeList ch = x.ChildNodes;
for (int i = 0; i < ch.Count; i++)
{
String att = "";
if (ch[i].Attributes != null)
{
for (int j = 0; j < ch[i].Attributes.Count; j++)
{
att += " "+ch[i].Attributes[j].Name + " " + ch[i].Attributes[j].Value;
}
textBox1.Text += "\r\n" + att ;
}
}
}
但我仍然无法访问<Overview name="UML2" >
及其子<Property name="actor2" value="2" />
。
答案 0 :(得分:1)
但今天的现代.net有一种更简单的方式。
var document = XDocument.Load(@"C:\Users\Administrator\Downloads\xxml\xxml\xml_file\uml.xml");
var element = document.XPathSelectElement("//Overview[@name='UML2']");
答案 1 :(得分:0)
我不是C#人,但我用Google搜索了“c#xpath”并找到了以下页面:http://support.microsoft.com/kb/308333
您可以使用以下XPath来访问您需要的XmlNode:
//Overview[@name/string() = 'UML2']
XPathNavigator nav;
XPathDocument docNav;
XPathNodeIterator NodeIter;
String strExpression;
// Open the XML.
docNav = new XPathDocument(@"C:\Users\Administrator\Downloads\xxml\xxml\xml_file\uml.xml");
// Create a navigator to query with XPath.
nav = docNav.CreateNavigator();
strExpression = "//Overview[@name/string() = 'UML2']";
NodeIter = nav.Select(strExpression);
我希望这会有所帮助。