10

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:

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
EnToutCas
  • 1,297
  • 2
  • 15
  • 20
  • which version of xpath are you using? xpath versions handle namespaces differently? – Jeremy French Feb 18 '09 at 16:32
  • Looks like I have to say: '//xmlns:anyType[@xsi:type="Document"]' for it to work – EnToutCas Feb 18 '09 at 17:19
  • Duped: - http://stackoverflow.com/questions/536441/xpath-namespace-driving-me-crazy - http://stackoverflow.com/questions/11345/xpaths-and-default-namespaces - http://stackoverflow.com/questions/103576/whats-wrong-with-my-xpath-xml – annakata Feb 18 '09 at 16:47

4 Answers4

18

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 );
David
  • 34,223
  • 3
  • 62
  • 80
0

This way you don't need to specify namespace:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("your xml");
XmlNode node = xmlDoc.SelectSingleNode("/*[local-name() = 'anyType']");
XmlNode nodeToImport = xmlDoc2.ImportNode(node, true);
xmlDoc2.AppendChild(nodeToImport);
Bruno B
  • 199
  • 1
  • 5
0

I think that

//anyType[namespace-uri() = "http://www.w3.org/2001/XMLSchema-instance"][local-name() = "type"]

Will do what you want.

Jeremy French
  • 11,707
  • 6
  • 46
  • 71
  • Thanks, I think what's wrong in my original expression is I need to prefix anyType with the namespace "xmlns". – EnToutCas Feb 18 '09 at 17:20
-1

Had nearly the same problem, I forgot to add the correct namespace for xsi:type (http://www.w3.org/2001/XMLSchema-instance) was using http://www.w3.org/2001/XMLSchema and I did never get any result - now it is working the following way:

<xsl:value-of select="/item1/item2/item3/@xsi:type"></xsl:value-of>
Andro Selva
  • 53,910
  • 52
  • 193
  • 240