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:

3

4 Answers 4

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 );
Sign up to request clarification or add additional context in comments.

3 Comments

What is up with a:anyType? Is that some sort of magic value?
No, that's the name of the XML element being sought in the above question.
ah, I see, didn't scroll over far enough
0

I think that

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

Will do what you want.

1 Comment

Thanks, I think what's wrong in my original expression is I need to prefix anyType with the namespace "xmlns".
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);

Comments

-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>

Comments

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.