Getting a single node from a C # XML document

I am trying to get a feed item from this document.

<rdf:RDF 
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" 
xmlns="http://purl.org/rss/1.0/" 
xmlns:slash="http://purl.org/rss/1.0/modules/slash/" 
xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" 
xmlns:dc="http://purl.org/dc/elements/1.1/" 
xmlns:syn="http://purl.org/rss/1.0/modules/syndication/" 
xmlns:admin="http://webns.net/mvcb/" 
xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">

    <channel rdf:about="http://developers.slashdot.org/">
     <title>Slashdot: Developers</title>
     <link>http://developers.slashdot.org/</link>
     ...

I think this is in the default namespace, which seems to be " http://purl.org/rss/1.0/ ", so I tried like this:

XmlNamespaceManager nsmsgr = new XmlNamespaceManager(rssDoc.NameTable);
nsmsgr.AddNamespace(String.Empty, "http://purl.org/rss/1.0/");

XmlNode root = rssDoc.DocumentElement;
XmlNode channel = rssDoc.SelectSingleNode("channel", nsmsgr);

I do not work. The XmlNode channel remains null.

+3
source share
3 answers

You cannot add it as Empty.

http://msdn.microsoft.com/en-us/library/system.xml.xmlnamespacemanager.addnamespace.aspx

, . String.Empty . . XmlNamespaceManager XML (XPath), . XPath , , (URI) . XPath XmlNamespaceManager, . XmlNode.SelectNodes XPathExpression.SetContext.XPathExpression.SetContext.

"default", "/*/default: channel".

:

        var nsmsgr = new XmlNamespaceManager(rssDoc.NameTable);
        nsmsgr.AddNamespace("default", "http://purl.org/rss/1.0/");

        var root = rssDoc.DocumentElement;
        var channel = rssDoc.SelectSingleNode("/*/default:channel", nsmsgr);

, URI, "", node. , :

        var nsmsgr = new XmlNamespaceManager(rssDoc.NameTable);
        var root = rssDoc.DocumentElement;
        nsmsgr.AddNamespace("default", root.GetAttribute("xmlns"));
        nsmsgr.AddNamespace("rdf", root.GetAttribute("xmlns:rdf"));
        var channel = rssDoc.SelectSingleNode("/rdf:RDF/default:channel", nsmsgr);
+3

:

XmlNode channel = rssDoc.SelectSingleNode(@"//channel");
-1
XmlElement root = rssDoc.DocumentElement;

XmlNode channel = root.SelectSingleNode("/channel");

This will give you a node channel, then you can reference attributes, value, InnerXML, FirstChild, etc. to pull data from that node.

* edit: should have been XmlElement instead of Node

-1
source

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


All Articles