gpt4 book ai didi

xml - 无法通过 XPathNavigator 读取 xml

转载 作者:数据小太阳 更新时间:2023-10-29 02:55:25 26 4
gpt4 key购买 nike

这是我的代码,不知道为什么不能通过XPathNavigator读取数据。但在我添加命名空间和模式之前已经很久了。

            XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add("http://www.somewhere.com", schemaPath);
settings.ValidationType = ValidationType.Schema;

XmlReader reader = XmlReader.Create(xmlPath, settings);

XPathDocument doc = new XPathDocument(reader);

XPathNavigator nav = doc.CreateNavigator();
XPathNodeIterator iter = nav.Select("/feeds/feed");

while (iter.MoveNext())
{
XPathNavigator feed = iter.Current.SelectSingleNode("name");
string name = feed.Value;
feed = iter.Current.SelectSingleNode("url");
string url = feed.Value;
feed = iter.Current.SelectSingleNode("url/@ver");
string version = feed.Value;
Console.WriteLine(name + ":" + url + ":" + version);}

XML:

<?xml version="1.0" encoding="utf-8"?>
<feeds xmlns="http://www.somewhere.com">
<feed>
<name>asdf</name>
<url ver="1.0">http://blogs.msdn.com/asdf/rss.xml</url>
</feed>
<feed>
<name>asdf 2</name>
<url ver="2.0">http://blogs.msdn.com/asdf2/rss.xml</url>
</feed>
</feeds>

和模式:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema
targetNamespace="http://www.somewhere.com"
elementFormDefault="qualified"
xmlns="http://www.somewhere.com"
xmlns:mstns="http://www.somewhere.com"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="feeds">
<xs:complexType >
<xs:sequence >
<xs:element name="feed" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="url">
<xs:complexType >
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="ver" type="xs:string" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

最佳答案

您可以将命名空间添加到 XPath:

var xPathNavigator = doc .CreateNavigator();
var xmlNamespaceManager = new XmlNamespaceManager(xPathNavigator.NameTable);
xmlNamespaceManager.AddNamespace("x", "http://www.somewhere.com");
xPathNavigator.Select("/x:feeds/x:feed", xmlNamespaceManager);

关于xml - 无法通过 XPathNavigator 读取 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1623549/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com