[英]Select Nodes Using XPath
I'm trying to select nodes using xpath in c# 我正在尝试在C#中使用xpath选择节点
This is my XML file 这是我的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>
This is my C# code which seems to not work 这是我的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);
}
What I want to output is every 4th field table name="xfile", like this: 我要输出的是每第四个字段表name =“ xfile”,如下所示:
This line here 1
This line here 2
Please let me know if you know a solution or a better way. 如果您知道解决方案或更好的方法,请告诉我。
First - you should provide just uri for namespace: 首先-您应该只为名称空间提供uri:
nsmgr.AddNamespace("ns", "http://schemas.microsoft.com/wix/2006/objects");
Second - you should use namespace when providing node name. 其次-在提供节点名称时应使用名称空间。 And table has attribute
name
instead of type
: 并且表具有属性
name
而不是type
:
XmlNodeList nodeList = root.SelectNodes("//ns:table[@name='XFile']/ns:row", nsmgr);
And last - after selecting row nodes, you should select fourth field node (which has full name ns:field
): 最后-在选择行节点之后,您应该选择第四个字段节点(其全名
ns:field
):
foreach (XmlNode row in nodeList)
{
XmlNode field = row.SelectSingleNode("(ns:field)[4]", nsmgr);
Console.WriteLine("Field: {0}", field.InnerText);
}
Output: 输出:
Field: This line here 1
Field: This line here 2
NOTE: You can get fields directly, without looping on rows: 注意:您可以直接获取字段,而无需在行上循环:
XmlNodeList fields =
root.SelectNodes("//ns:table[@name='XFile']/ns:row/ns:field[4]", nsmgr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.