【发布时间】:2019-06-22 07:24:48
【问题描述】:
这是我的测试 XML 文档:
<?xml version="1.0" encoding="utf-8" ?>
<foos>
<foo>
<bar>
<bazs>
<baz>baz1</baz>
<baz>baz2</baz>
<baz>baz3</baz>
</bazs>
</bar>
</foo>
<!--there will be other foo nodes with same structure but different number of baz nodes-->
</foos>
在本文档中,每个<foo> 节点都有一个<bar> 节点,每个<bar> 节点都有一个<baz> 节点列表。我想从每个<bar> 访问这些<baz> 节点。这是我的代码:
using System;
using System.Xml;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load("test.xml");
XmlNodeList fooNodes = xmlDocument.SelectNodes("/foos/foo");
foreach(XmlNode fooNode in fooNodes)
{
XmlNode barNode = fooNode.SelectSingleNode("bar");
var bazNodes1 = fooNode.SelectNodes("/bar/bazs/baz");
var bazNodes2 = fooNode.SelectNodes("bar/bazs/baz");
var bazNodes3 = barNode.SelectNodes("/bazs/baz");
Console.WriteLine($"Method 1 returned {bazNodes1.Count} nodes.");
Console.WriteLine($"Method 2 returned {bazNodes2.Count} nodes.");
Console.WriteLine($"Method 3 returned {bazNodes3.Count} nodes.");
}
Console.Read();
}
}
}
,产生:
Method 1 returned 0 nodes.
Method 2 returned 3 nodes.
Method 3 returned 0 nodes.
在这里,我对在寻址节点时使用/ 有点困惑。虽然从文档的根目录获取 fooNodes 正在使用 /foos/foo 作为 xpath ,但我无法从 <foo> 节点使用 /bar/bazs/baz 获取 bazNodes ,这对我来说很奇怪。而且我还坚持从<bar> 节点获取bazNodes,我认为这是因为我不知道正确的语法。所以我的问题是:
- 在寻址节点时,我应该在什么时候包含前导
/? - 在此示例中,如何从
<bar>节点获取<baz>节点?
【问题讨论】:
标签: c# xml xml-parsing