Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

XPath on an XML document with namespace

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:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...