如何从LINQ到XML中的XElement读取特定元素值 [英] How to Read a specific element value from XElement in LINQ to XML

查看:673
本文介绍了如何从LINQ到XML中的XElement读取特定元素值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 XElement ,其中有这样的内容。

I have an XElement which has content like this.

<Response xmlns="someurl" xmlnsLi="thew3url">
   <ErrorCode></ErrorCode>
   <Status>Success</Status>
   <Result>
       <Manufacturer>
            <ManufacturerID>46</ManufacturerID>
            <ManufacturerName>APPLE</ManufacturerName>
       </Manufacturer>
      //More Manufacturer Elements like above here
   </Result>
</Response>

如何读取状态元素?

我尝试了 XElement stats = myXel.Descendants(Status)。SingleOrDefault(); 正在返回null。

I tried XElement stats = myXel.Descendants("Status").SingleOrDefault(); But that is returning null.

推荐答案

XElement response = XElement.Load("file.xml"); // XElement.Parse(stringWithXmlGoesHere)
XNamespace df = response.Name.Namespace;
XElement status = response.Element(df + "Status");

应足以访问状态子元素中。
如果你想要该元素的值作为字符串,然后做例如

should suffice to access the Status child element. If you want the value of that element as a string then do e.g.

string status = (string)response.Element(df + "Status");

这篇关于如何从LINQ到XML中的XElement读取特定元素值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆