【问题标题】:XPath on an XML document with namespace具有命名空间的 XML 文档上的 XPath
【发布时间】:2010-10-08 09:21:40
【问题描述】:

我有这个带有命名空间的 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"]

它不起作用:

【问题讨论】:

标签: xml xpath namespaces


【解决方案1】:

如果您使用的是 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 );

【讨论】:

  • a:anyType 怎么了?这是某种神奇的价值吗?
  • 不,这是上述问题中要查找的 XML 元素的名称。
  • 啊,我明白了,滚动的不够远
【解决方案2】:

我认为

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

会做你想做的。

【讨论】:

  • 谢谢,我认为我原来的表达有什么问题是我需要在 anyType 前面加上命名空间“xmlns”。
【解决方案3】:

遇到了几乎相同的问题,我忘记为 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>

【讨论】:

    【解决方案4】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-09-17
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      • 2010-10-22
      • 2011-01-05
      相关资源
      最近更新 更多