XPathNavigator Help

Here is an example of the XML I'm working with (retrieved from any Special: Export / SomePage wiki):

<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.4/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.4/ http://www.mediawiki.org/xml/export-0.4.xsd" version="0.4" xml:lang="en"> 
  <siteinfo> 
    <sitename>Wikipedia</sitename> 
    <base>http://en.wikipedia.org/wiki/Main_Page</base> 
    <generator>MediaWiki 1.16wmf4</generator> 
    <case>first-letter</case> 
    <namespaces> 
      <namespace key="-2" case="first-letter">Media</namespace> 
      <namespace key="-1" case="first-letter">Special</namespace> 
      <namespace key="0" case="first-letter" /> 
      ...
    </namespaces> 
  </siteinfo> 
</mediawiki> 

I have tried everything I can think of to "go" directly to the siteinfo node and iterate over the results, and nothing works unless I manually move through each child element of the node from the root down. I tried a million variations of the various .Move * and .Select * methods, and it seems like I'm just throwing my head on the wall, but my current version looks like this:

StringReader strr = new StringReader(_rawData);
XPathDocument xd = new XPathDocument(XmlReader.Create(strr, Bot.XmlReaderSettings));
XPathNavigator xn = xd.CreateNavigator();
XPathNodeIterator xni = xn.Select("/mediawiki/siteinfo");
foreach (XPathNavigator nav in xni)
    Console.WriteLine(nav.LocalName);

This does not return any results. What am I doing wrong?

+3
source share
1 answer

XML. xmlns . , :

using (var r = File.OpenText("test.xml")) {
    XPathDocument xd = new XPathDocument(XmlReader.Create(r));
    XPathNavigator xn = xd.CreateNavigator();

    XmlNamespaceManager nsmgr = new XmlNamespaceManager(xn.NameTable);
    nsmgr.AddNamespace("mw", "http://www.mediawiki.org/xml/export-0.4/");

    XPathNodeIterator xni = xn.Select("/mw:mediawiki/mw:siteinfo", nsmgr);

    foreach (XPathNavigator nav in xni)
        Console.WriteLine(nav.Name);
}

, : MSDN: XML XPath XSLT.

+9

Source: https://habr.com/ru/post/1774821/


All Articles