XmlDocument - SelectSingleNode with namespace

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 does not work:

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

What is the way to handle the xmlns attribute and how to parse it?

Does this have anything to do with the 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);

It's all XPath more complex than it sounds, I would recommend for beginners, like mine, to read: http://www.w3schools.com/xpath/xpath_syntax.asp

+4
source share
3 answers

You need to add an instance of XmlNamespaceManager to the game:

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);
  }

}

}

http://msdn.microsoft.com/es-es/library/4bektfx9(v=vs.110).aspx

+4
source

Here's 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"));
0
source

xmlns XHTML . :

XDocument xdoc = XDocument.Load(xmlPath);
var attrib = xdoc.Root.Attribute("xmlns").Value;
-1

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


All Articles