我在使用XPathNodeIterator从给定路径中获取数据时遇到问题。调试时,pNav具有xml文件中的所有值。但是,迭代器的计数为0。它永远不会进入while循环。任何帮助,将不胜感激。
C#
XPathDocument pdoc = new XPathDocument("Courses.xml");
XPathNavigator pNav = pdoc.CreateNavigator();
XPathNodeIterator iterator = pNav.Select("/Courses/Course");
while (iterator.MoveNext())
{
XPathNodeIterator it = iterator.Current.Select("Name");
it.MoveNext();
string courseName = it.Current.Value;
it = iterator.Current.Select("Code");
it.MoveNext();
string courseCode = it.Current.Value;
Console.WriteLine("{0} {1}", courseName, courseCode);
}
XML:
<Courses xmlns="http://xml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="Courses.xsd">
<Course>
<Code Undergrad="240"/>
<Name>Biology</Name>
<Instructor>
<Name>
<First>John</First>
<Last>Doe</Last>
</Name>
<Contact>
<Phone>898-989-8989</Phone>
</Contact>
</Instructor>
<Room>515</Room>
</Course>
我希望输出是
Name = Biology, Code = 240
因为您有
xmlns="http://xml"
在XML文件中,您需要添加XmlNamespaceManager
以允许导航器找到节点。如果从XML中删除xmlns="http://xml"
,则不需要使用XmlNamespaceManager
。
也Select
方法返回节点的集合-您需要调用SelectSingleNode
以获取所需的节点。 E.G。
XPathDocument pdoc = new XPathDocument("Courses.xml");
XPathNavigator pNav = pdoc.CreateNavigator();
var manager = new XmlNamespaceManager(pNav.NameTable);
manager.AddNamespace("cs", "http://xml");
XPathNodeIterator iterator = pNav.Select("/cs:Courses/cs:Course", manager);
while(iterator.MoveNext())
{
var nameNode = iterator.Current.SelectSingleNode("cs:Name", manager);
string courseName = nameNode.Value;
var codeNode = iterator.Current.SelectSingleNode("cs:Code", manager);
codeNode.MoveToFirstAttribute();
string courseCode = codeNode.Value;
Console.WriteLine("{0} {1}", courseName, courseCode);
}
[当您到达Code
元素时,您需要移至第一个属性以获取该值,否则Value
属性将返回一个空字符串
需要将namespace resolver传递给选择方法:
const string xml = @"
<Courses xmlns=""http://xml"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""Courses.xsd"">
<Course>
<Code Undergrad=""240""/>
<Name>Biology</Name>
<Instructor>
<Name>
<First>John</First>
<Last>Doe</Last>
</Name>
<Contact>
<Phone>898-989-8989</Phone>
</Contact>
</Instructor>
<Room>515</Room>
</Course>
<Course>
<Code Undergrad=""000""/>
<Name>Math</Name>
<Instructor>
<Name>
<First>John</First>
<Last>Doe</Last>
</Name>
<Contact>
<Phone>898-989-8989</Phone>
</Contact>
</Instructor>
<Room>515</Room>
</Course>
</Courses>";
using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(xml)))
{
var pdoc = new XPathDocument(stream);
var pNav = pdoc.CreateNavigator();
var manager = new XmlNamespaceManager(pNav.NameTable);
manager.AddNamespace("cs", "http://xml");
var iterator = pNav.Select("/cs:Courses/cs:Course", manager);
foreach (XPathNavigator node in iterator)
{
var courseName = node.SelectSingleNode("cs:Name", manager)?.Value;
var courseCode = node.SelectSingleNode("cs:Code", manager)?.GetAttribute("Undergrad", string.Empty);
Console.WriteLine("{0} {1}", courseName, courseCode);
}
}