XPath on an XML document with namespace

17,922

If you are using C# then you need to specify the namespace for the "anyType" element in your XPath:

var xml = new XmlDocument();
xml.LoadXml( "your xml" );
var names = new XmlNamespaceManager( xml.NameTable );
names.AddNamespace( "xsi", "http://www.w3.org/2001/XMLSchema-instance" );
names.AddNamespace( "a", "http://tempuri.org/" );
var nodes = xml.SelectNodes( "//a:anyType[@xsi:type='Document']", names );
Share:
17,922
EnToutCas
Author by

EnToutCas

Updated on July 18, 2022

Comments

  • EnToutCas
    EnToutCas almost 2 years

    I'm having this XML document with namespaces and I want to extract some nodes using XPath.

    Here's the document:

    <ArrayOfAnyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
      <anyType xsi:type="Document">
        <Id>5</Id>
        <Title>T1</Title>
      </anyType>
    
      <anyType xsi:type="Document">
        <Id>15</Id>
        <Title>T15</Title>
      </anyType>
    </ArrayOfAnyType>
    

    What's the XPath expression going to be if I want to extract all "anyType" elements with xsi:type="Document"?

    I've tried this:

    //anyType[@xsi:type="Document"]
    

    and it doesn't work:

  • EnToutCas
    EnToutCas about 15 years
    Thanks, I think what's wrong in my original expression is I need to prefix anyType with the namespace "xmlns".
  • jcollum
    jcollum almost 9 years
    What is up with a:anyType? Is that some sort of magic value?
  • Ashwani
    Ashwani almost 9 years
    No, that's the name of the XML element being sought in the above question.
  • jcollum
    jcollum almost 9 years
    ah, I see, didn't scroll over far enough