【问题标题】:Duplicate: XPath expressions with default namespace重复:具有默认命名空间的 XPath 表达式
【发布时间】:2011-09-22 08:29:43
【问题描述】:

我目前正在编写一个允许我从 OData 提要构造实体的 C# 类。 不要问为什么,我现在就需要它:)

XML 的 sn-p 如下所示:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<entry xml:base="http://demo.tenforce.acc/Api.svc/" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">
  <id>http://demo.tenforce.acc/Api.svc/Items(387)</id>
  <title type="text"></title>
  <updated>2011-09-22T07:35:54Z</updated>
  <author>
    <name />
  </author>
  <link rel="edit" title="Item" href="Items(387)" />
  <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Children" type="application/atom+xml;type=feed" title="Children" href="Items(387)/Children" />
  <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Parent" type="application/atom+xml;type=entry" title="Parent" href="Items(387)/Parent" />
  <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Attachments" type="application/atom+xml;type=feed" title="Attachments" href="Items(387)/Attachments" />
  <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Predecessors" type="application/atom+xml;type=feed" title="Predecessors" href="Items(387)/Predecessors" />
  <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Successors" type="application/atom+xml;type=feed" title="Successors" href="Items(387)/Successors" />
  <category term="TenForce.Execution.Api2.Objects.Item" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
  <content type="application/xml">
    <m:properties>
      <d:Id m:type="Edm.Int32">387</d:Id>
    </m:properties>
  </content>
</entry>

我创建了一个代码 sn-p,它将整个 xml 字符串加载到一个 XmlDocument 中,并生成一个 XmlNamespaceManager 以访问各种命名空间。

我正在尝试从 XML 中选择 &lt;category&gt; 元素,但我似乎无法正确获取 Xpath 表达式。我尝试了以下方法:

  • //条目/类别
  • 后代::xmlns:cateogry
  • //d:类别
  • //m:类别
  • //类别
  • //xml:类别

但似乎没有选择有问题的节点。

【问题讨论】:

标签: c# .net xml xpath odata


【解决方案1】:

哦,没关系,我找到了解决方案。 我必须为原子元素添加命名空间......

var manager = new XmlNamespaceManager(_mDocument.NameTable);
manager.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
manager.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
manager.AddNamespace("atom", "http://www.w3.org/2005/Atom");

这让我可以使用 //atom:category 选择 &lt;category&gt; 元素

【讨论】:

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