Frage

Ich weiß, dass diese Frage zuvor auf ähnliche Weise gefragt wurde, aber ich kann diese Arbeit nicht zu bekommen.

Ich habe etwas XML: generasacodicetagpre.

und ich versuche, Werte mit XPath zu lesen: generasacodicetagpre.

Aber sogar eine einfache Auswahl des Root-Knotens gibt NULL zurück!Ich bin mir sicher, dass ich mit meinem Namenspace etwas nicht stimmt.Kann jemand bitte helfen?

Idealerweise möchte ich einfache Linien, mit denen ich Werte aus der XML-Datei auswählen können, d. H. generasacodicetagpre.

btw, ich habe keine (direkte) Steuerung über den XML-Dateiinhalt.

War es hilfreich?

Lösung

I don't believe you can use an empty namespace alias and have it used automatically by the XPath expression. As soon as you use an actual alias, it should work though. This test is fine, for example:

using System;
using System.Xml;
using System.Xml.XPath;

class Test
{
    static void Main() 
    {
        string xmlFile = "test.xml";
        XPathDocument xmldoc = new XPathDocument(xmlFile); 
        XPathNavigator nav = xmldoc.CreateNavigator(); 
        XmlNamespaceManager nsMgr = new XmlNamespaceManager(nav.NameTable);
        nsMgr.AddNamespace("x", "http://www.rixml.org/2005/3/RIXML"); 
        XPathNavigator result = nav.SelectSingleNode("/x:Research", nsMgr);
        Console.WriteLine(result);
    }
}

Do you have to use XPath and XPathDocument, by the way? I tend to find that LINQ to XML is a much more pleasant API, particularly when it comes to namespaces. If you're using .NET 3.5 and you have no particular requirement to use XPath, I'd suggest you check it out.

Andere Tipps

Make the following changes

nsMgr.AddNamespace("x", "http://www.rixml.org/2005/3/RIXML"); 
XPathNavigator result = nav.SelectSingleNode("/x:Research", nsMgr);

i could post, and answer my own question, for the native equivalent of this code. Instead i'll just add it as an answer to the end.

When using the native IXMLDOMDocument (version 6) object:

//Give the default namespace as alias of "x"
document.setProperty("SelectionNamespaces","xmlns:x='http://www.rixml.org/2005/3/RIXML'");

//Query for the nodes we want
document.selectSingleNode("/x:Research");

Bonus Question: Why, oh why, does no Xml Document object model query the default namespace when no namespace is specified... sigh

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top