2

I receive an XML file which has on the root node a xmlns namespace assigned:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Message xmlns="http://www.myAddress.com/DataRequest/message/">
  <Date>2017/01/01</Date>
</Message>  

I do not know how to retrive the Date element using XPath, I tried

  var root = xDocument.Root;
  var dateElement = root.XPathSelectElement("/Message/Date");

If I remove the namespace from the root xml, then I can retrieve the value using "/Message/Date".

I tried to add xmlns to a XmlNamespaceManager, but I get this error:

Prefix "xmlns" is reserved for use by XML.

How can I get the value?

1

2 Answers 2

7

You should use namespace when you specify element's name. Default namespace is easy to get with XElement.GetDefaultNamespace() method:

var ns = root.GetDefaultNamespace();
var dateElement = (DateTime)root.Element(ns + "Date");

If you want to use XPath:

XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable());
manager.AddNamespace("ns", root.GetDefaultNamespace().ToString());
var dateElement = (DateTime)root.XPathSelectElement("/ns:Message/ns:Date", manager);
Sign up to request clarification or add additional context in comments.

3 Comments

I doesn't work and I do not understand why it should work. There are no nodes in XML file defined with the namespace prefix I add to XmlNamespaceManager.
@Angela it works and I don't understand why it shouldn't work. Have you tried running this code?
I just tried it out in LinqPad and can confirm that both Sergey's suggestions work.
0

I would suggest using LINQ.

Here is a link to the code example:https://msdn.microsoft.com/en-us/library/mt693115.aspx

here is the code:

XElement root = XElement.Load("Message.xml");  
IEnumerable<XElement> dateNode=  
    from el in root.Elements("Date")   
    select el;  
foreach (XElement el in dateNode)  
    Console.WriteLine(el);  

2 Comments

You still need to take care of the namespace. So add var ns = root.GetDefaultNamespace(); and from el in root.Elements(ns+"Date")
this is a duplicate question, stackoverflow.com/questions/4857172/…. @PalleDue good call

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.