XElement-读取节点C#
本文关键字:节点 读取 XElement- | 更新日期: 2023-09-27 18:20:13
我有一个类似以下的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>
元素作为根属性。
XElement允许您跳过这一步,它可以同时充当Document和root。修复非常简单:
XElement productFeed = root; //.Element("productfeed");
XElement
和XDocument
解析相同的内容,但XDocument有一个(更完整的)文档包装器,在处理<? >
处理指令等时需要它。