问题描述
我正在尝试使用LINQ-to-XML(XElement对象)查找元素的内部文本值.我进行服务调用,并返回一个XML响应,该响应已成功加载到XElement对象中.我想提取其中一个元素的内部文本-但是,每次尝试执行此操作时,都会得到空结果.
I'm trying to find the inner text value of an element using LINQ-to-XML (an XElement object). I make my service call and get an XML response back that I've successfully loaded into an XElement object. I want to extract the inner text of one of the elements - however, every time I try to do this, I get a null result.
我觉得我缺少一些超级简单的东西,但是对于LINQ-to-XML来说我还是很陌生.感谢您的帮助.
I feel like I'm missing something super-simple, but I'm fairly new to LINQ-to-XML. Any help is appreciated.
我正在尝试获取StatusInfo/Status元素的内部文本值.这是我返回的XML文档:
I'm trying to get the inner text value of the StatusInfo/Status element. Here's my XML document that's returned:
<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>
这是我用来提取值的代码片段(无效):
Here's a snippet of code that I'm using to extract the value (which doesn't work):
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
.我不知道我是否处理正确,还是有更好的方法来处理这个问题.
My status
variable is always null
. I've tried several variations on this, but to no avail. The part that's confusing me is the namespace -- tag
and 2008
are defined. I don't know if I'm handling this correctly or if there's a better way to deal with this.
此外,我无法控制XML模式或XML结构.我正在使用的服务是我无法控制的.
Also, I don't have control over the XML schema or the structure of the XML. The service I'm using is out of my control.
感谢您的帮助!
推荐答案
尝试使用Descendants()
代替Elements()
:
XElement x = XElement.Load(responseReader);
XNamespace ns = "tag:foo.com,2008:/my/data";
var status = x.Descendants(ns + "Status").FirstOrDefault().Value;
这篇关于如何使用两个名称空间查询XElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!