user603007
user603007

Reputation: 11794

xml how to select node with namespace in front?

I have this xml:

XNamespace g = "http://something.com";
XElement contacts =
    new XElement("Contacts", new XAttribute(XNamespace.Xmlns + "g", g),
        new XElement("Contact",
            new XElement(g + "Name", "Patrick Hines"),
            new XElement("Phone", "206-555-0144"),
            new XElement("Address",
                new XElement("street", "this street"))

        )
    );

I would like to select the gName element so I tried but does not work:

var node = doc.SelectSingleNode("/Contacts/g:Name[text()=Patrick Hines');

Upvotes: 0

Views: 63

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

You're mixing LINQ to XML (XElement class) and old-fashioned XmlDocument with SelectSingleNode method.

You should use XNode.XPathSelectElement method instead, but with namespace it's a little bit more tricky then just a method call.

First of all, you have to create IXmlNamespaceResolver instance using XmlReader.NameTable property:

var reader = doc.CreateReader();
var namespaceManager = new XmlNamespaceManager(reader.NameTable);
namespaceManager.AddNamespace("g", g.NamespaceName);

And with that you can query your document:

var doc = new XDocument(contacts);
var node = doc.XPathSelectElement("/Contacts/Contact/g:Name[text()='Patrick Hines']", namespaceManager);

Upvotes: 1

Related Questions