[英]Select Nodes Using XPath
我正在尝试在C#中使用xpath选择节点
这是我的XML文件
<?xml version="1.0" encoding="utf-8"?>
<xObject version="3.0.2002.0" xmlns="http://schemas.microsoft.com/wix/2006/objects">
<section id="*" type="product">
<table name="NotThis">
<row sourceLineNumber="D:\bla\bla\">
<field>Borderish.fo</field>
<field>Documents</field>
<field>1</field>
<field>No, not this line here 1</field>
</row>
<row sourceLineNumber="D:\blah\blah\">
<field>Charterish</field>
<field>Documents</field>
<field>1</field>
<field>No not, this line here 2</field>
</row>
</table>
<table name="XFile">
<row sourceLineNumber="D:\bla\bla\">
<field>Borderish.fo</field>
<field>Documents</field>
<field>1</field>
<field>This line here 1</field>
</row>
<row sourceLineNumber="D:\blah\blah\">
<field>Charterish</field>
<field>Documents</field>
<field>1</field>
<field>This line here 2</field>
</row>
</table>
</section>
</xObject>
这是我的C#代码,似乎不起作用
XmlDocument doc = new XmlDocument();
doc.Load("Testing.xml");
XmlNode root = doc.DocumentElement;
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("ns", "xmlns="http://schemas.microsoft.com/wix/2006/objects"");
XmlNodeList nodeList = root.SelectNodes("ns:table[@type='XFile']/ns:row", nsmgr);
foreach (XmlNode xn in nodeList)
{
string fieldLine = xn["Field"].InnerText;
Console.WriteLine("Field: {4}", fieldLine);
}
我要输出的是每第四个字段表name =“ xfile”,如下所示:
This line here 1
This line here 2
如果您知道解决方案或更好的方法,请告诉我。
首先-您应该只为名称空间提供uri:
nsmgr.AddNamespace("ns", "http://schemas.microsoft.com/wix/2006/objects");
其次-在提供节点名称时应使用名称空间。 并且表具有属性name
而不是type
:
XmlNodeList nodeList = root.SelectNodes("//ns:table[@name='XFile']/ns:row", nsmgr);
最后-在选择行节点之后,您应该选择第四个字段节点(其全名ns:field
):
foreach (XmlNode row in nodeList)
{
XmlNode field = row.SelectSingleNode("(ns:field)[4]", nsmgr);
Console.WriteLine("Field: {0}", field.InnerText);
}
输出:
Field: This line here 1
Field: This line here 2
注意:您可以直接获取字段,而无需在行上循环:
XmlNodeList fields =
root.SelectNodes("//ns:table[@name='XFile']/ns:row/ns:field[4]", nsmgr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.