3

我正在尝试使用 LINQ-to-XML(一个 XElement 对象)查找元素的内部文本值。我进行了服务调用并获得了一个已成功加载到 XElement 对象中的 XML 响应。我想提取其中一个元素的内部文本 - 但是,每次我尝试这样做时,我都会得到一个空结果。

我觉得我错过了一些超级简单的东西,但我对 LINQ-to-XML 还是很陌生。任何帮助表示赞赏。

我正在尝试获取 StatusInfo/Status 元素的内部文本值。这是我返回的 XML 文档:

<feed xml:lang="en-us" xmlns="http://www.w3.org/2005/Atom">
  <title type="text">My Response</title>
  <id>tag:foo.com,2012:/bar/06468dfc-32f7-4650-b765-608f2b852f22</id>
  <author>
    <name>My Web Services</name>
  </author>
  <link rel="self" type="application/atom+xml" href="http://myServer/service.svc/myPath" />
  <generator uri="http://myServer" version="1">My Web Services</generator>
  <entry>
    <id>tag:foo.com,2012:/my-web-services</id>
    <title type="text" />
    <updated>2012-06-27T14:22:42Z</updated>
    <category term="tag:foo.com,2008/my/schemas#system" scheme="tag:foo.com,2008/my/schemas#type" />
    <content type="application/vnd.my.webservices+xml">
      <StatusInfo xmlns="tag:foo.com,2008:/my/data">
        <Status>Available</Status>  <!-- I want the inner text -->
      </StatusInfo>
    </content>
  </entry>
</feed>

这是我用来提取值的一段代码(不起作用):

    XElement root = XElement.Load(responseReader);
    XNamespace tag = "tag:foo.com,2008:/my/data";
    var status = (from s in root.Elements(tag + "Status")
                 select s).FirstOrDefault();

我的status变量总是null. 我已经尝试了几种变体,但无济于事。让我感到困惑的部分是名称空间——tag并且2008已定义。我不知道我是否正确处理了这个问题,或者是否有更好的方法来处理这个问题。

此外,我无法控制 XML 模式或 XML 的结构。我正在使用的服务不受我控制。

谢谢你的帮助!

4

2 回答 2

2

尝试Descendants()代替Elements()

XElement x = XElement.Load(responseReader);
XNamespace ns = "tag:foo.com,2008:/my/data";
var status = x.Descendants(ns + "Status").FirstOrDefault().Value;
于 2012-06-27T16:53:11.770 回答
0

提要中有 2 个命名空间:

  1. Atom 命名空间
  2. 标签命名空间

外层 xml 需要使用 Atom 命名空间,而内层 xml 的一部分需要使用标签命名空间。IE,

var doc = XDocument.Load(responseReader);
XNamespace nsAtom = "http://www.w3.org/2005/Atom";
XNamespace nsTag = "tag:foo.com,2008:/my/data";

// get all entry nodes / use the atom namespace
var entry = doc.Root.Elements(nsAtom + "entry");

// get all StatusInfo elements / use the atom namespace
var statusInfo = entry.Descendants(nsTag + "StatusInfo");

// get all Status / use the tag namespace
var status = statusInfo.Elements(nsTag + "Status");

// get value of all Status
var values = status.Select(x => x.Value.ToString()).ToList();
于 2012-06-27T17:08:18.930 回答