Can't read xml through XPathNavigator
Here is my code, I don't know why I can't read the data through XPathNavigator. But it was well before I add namespace and schema.
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);}
The 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>
and schema:
<?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 na开发者_如何学Gome="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>
You can add the namespace to the 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);
精彩评论