Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlDocument - SelectSingleNode with namespace

Tags:

c#

This is my code:

XmlTextReader reader = new XmlTextReader(xmlPath);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
XmlNode root = xmlDoc.DocumentElement;

XmlNode node = root.SelectSingleNode("marketingid");

XML that works:

<confirmsubmit>
    <marketingid>-1</marketingid>
</confirmsubmit>

XML that doesn't work:

<confirmsubmit xmlns="http:....">
    <marketingid>-1</marketingid>
</confirmsubmit>

What is the way to deal with the xmlns attribute and how can i parse it?

Is it has anything to do with namespace?

EDIT: This is the code that works:

XmlTextReader reader = new XmlTextReader(xmlPath);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);

XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("ns", xmlDoc.DocumentElement.NamespaceURI);

XmlNode book = xmlDoc.SelectSingleNode("/ns:confirmsubmit/ns:marketingid", nsmgr);

This all XPath is more complicated than seems, I would recommand to begginers like my to read: http://www.w3schools.com/xpath/xpath_syntax.asp

like image 991
omriman12 Avatar asked Mar 20 '14 13:03

omriman12


2 Answers

You need to add a XmlNamespaceManager instance in the game, as shown in this example from the documentation:

public class Sample
{
    public static void Main()
    {

      XmlDocument doc = new XmlDocument();
      doc.Load("booksort.xml");

      //Create an XmlNamespaceManager for resolving namespaces.
      XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
      nsmgr.AddNamespace("bk", "urn:samples");

      //Select and display the value of all the ISBN attributes.
      XmlNodeList nodeList;
      XmlElement root = doc.DocumentElement;
      nodeList = root.SelectNodes("/bookstore/book/@bk:ISBN", nsmgr);
      foreach (XmlNode isbn in nodeList){
        Console.WriteLine(isbn.Value);
      }

    }
}
like image 200
Oscar Avatar answered Sep 22 '22 18:09

Oscar


Here is how to do it from LINQ to XML. Short and simple

const string xml = @"<confirmsubmit xmlns='http:....'>
                       <marketingid>-1</marketingid>
                     </confirmsubmit>";

XElement element = XElement.Parse(xml);
var requestedElement = element.Elements().FirstOrDefault(x => x.Name.LocalName.Equals("marketingid"));
like image 45
SirH Avatar answered Sep 19 '22 18:09

SirH