繁体   English   中英

XElement-读取节点C#

[英]XElement - reading the nodes C#

我有一个如下的XML:

<?xml version="1.0"?>
<productfeed>
    <product>
        <name>x</name>
        <etc>z</etc>
    </product>
    <product>
        <name>x</name>
        <etc>z</etc>
    </product>
</productfeed>

我今天尝试使用LINQ和XElement从XML检索数据。 我设法加载文件,但是无法访问productfeed节点(它返回null)。 有趣的是,我可以直接从根开始遍历product节点,而我读到不应跳过那样。 我是否会错误地解释某些内容,也许productfeed节点已经在根目录中,但是我将如何获取其纯内容?

XElement root = XElement.Load("...path..."); // works
XElement productFeed = root.Element("productfeed"); // returns null
IEnumerable<XElement> products = root.Elements("product"); // works

正式地,您应该将其加载到XDocument中。 那本来会有<productfeed>元素作为Root属性。

XElement让您跳过此步骤,它可以同时充当Document和root。 解决方法非常简单:

XElement productFeed = root; //.Element("productfeed"); 

XElementXDocument可以解析相同的内容,但是XDocument具有(更完整的)文档包装器,在处理<? >时需要使用它<? > <? >加工说明等

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM