带有命名空间的XML文档上的XPath

时间:2009-02-18 16:28:04

标签: xml xpath namespaces

我正在使用带有命名空间的XML文档,我想使用XPath提取一些节点。

这是文件:

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

如果我想用xsi:type =“Document”提取所有“anyType”元素,XPath表达式会是什么?

我试过这个:

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

并且不起作用:

4 个答案:

答案 0 :(得分:17)

如果您使用的是C#,则需要为XPath中的“anyType”元素指定命名空间:

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

答案 1 :(得分:0)

我认为

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

会做你想做的事。

答案 2 :(得分:0)

这样您就不需要指定命名空间:

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

答案 3 :(得分:-1)

几乎同样的问题,我忘了为xsi:type添加正确的命名空间 (http://www.w3.org/2001/XMLSchema-instance)正在使用http://www.w3.org/2001/XMLSchema 我从来没有得到任何结果 - 现在它的工作方式如下:

<xsl:value-of select="/item1/item2/item3/@xsi:type"></xsl:value-of>