如何使用Xelement读取子节点? [英] How Do I Read Child Nodes Using Xelement?

查看:745
本文介绍了如何使用Xelement读取子节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现这段代码。目标是从其中一个节点获取价值。

I have this piece of code that I am trying to implement.The objective is to get value from one of the nodes.

string str1 = obj.GetStatusSettingsFromCamera("http://10.40.160.73/cgi/status.php?item=mfm&format=xml", "", "");
            XElement xml = XElement.Parse(str1);
            XElement findTag = xml.Elements("Firmware_CRC").FirstOrDefault();

            if (findTag != null) \\ showing null 
            {
                string firmwareTitle =Convert.ToString(findTag.Attribute("title"));
                string currentFirmware = findTag.Value;
            }







来自网址的XML;






XML from URL;

<Status>
<Summary>
<Uptime>09:56:12</Uptime>
<FastWD>00:01:58</FastWD>
<SlowWD>14:03:48</SlowWD>
<Configuration_Download>Success</Configuration_Download>
<Firmware_CRC title="Compatible versions: a29d.fe3e" class="critical hastooltip">a29d.3db8</Firmware_CRC>
<Core_Version>19.6</Core_Version>
<App_Version>23.4</App_Version>
<CPLD_Version>4BF44D51</CPLD_Version>
</Summary>
<Detectors>
<state>Operating</state>
<detector>8 channel - Lane agile radar: Operating</detector>
<detector>1 channel - Wired light phase detector: Operating</detector>
<detector>Optical Light Phase Detector: Absent</detector>
<self_test>pass[00]</self_test>
<radar_error_counter>0</radar_error_counter>
</Detectors>
</Status>





如果我试图找到Firmware_CRC,则findtag显示为null。它是Summary下的一个子节点。

我知道我在某个地方出错但无法理解它。

P.S. :我是.NET的新手



If I try to find Firmware_CRC the findtag is showing null. It's a child node under Summary.
I know I am going wrong somewhere but can't figure it out.
P.S. : I am new to .NET entirely

推荐答案

元素方法 [ ^ ]仅查找作为指定节点的直接子节点的元素。它会找到< Summary> < Detectors> 元素,但不适用于这些元素。



尝试使用 Descendants 方法 [ ^ ]而不是:

The Element method[^] only looks for elements which are direct children of the specified node. It would find the <Summary> and <Detectors> elements, but won't work for the children of those elements.

Try using the Descendants method[^] instead:
XElement findTag = xml.Descendants("Firmware_CRC").FirstOrDefault();


XElement findTag = xml.Elements( // Firmware_CRC)。FirstOrDefault(); (谢谢理查德)



我会使用支持XPath的方法 - 在需要时提供更大的灵活性:



XElement findTag = xml.XPathSelectElements( // Firmware_CRC)。FirstOrDefault();







//从当前节点中选择与选择匹配的文档中的节点,无论它们在何处





http://www.w3schools.com/xpath/xpath_intro.asp [ ^ ]
XElement findTag = xml.Elements("//Firmware_CRC").FirstOrDefault(); (Thanks, Richard)

I'd use a method that supports XPath -- for more flexibility when needed:

XElement findTag = xml.XPathSelectElements("//Firmware_CRC").FirstOrDefault();


"
// Selects nodes in the document from the current node that match the selection no matter where they are
"

http://www.w3schools.com/xpath/xpath_intro.asp[^]


这篇关于如何使用Xelement读取子节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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