2015-11-02 85 views
1

我有一个XML象下面这样:的XElement - 读节点C#

<?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 
+1

检查XElement.Document属性。我想这就是你要找的。 –

+3

'root'是''。 – PetSerAl

+0

获取“纯内容”是什么意思? – TKharaishvili

回答

2

正式地,您应该将其加载到XDocument中。这将有一个<productfeed>元素作为Root属性。

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

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

XElementXDocument做解析相同的内容,但的XDocument有一个(更完整)文件的包装,您将需要与<? >处理指令等交易时

+0

作为以前的评论的答案是有用的。但是,如果我尝试:XElement root = XElement(“.. path ..”);或XDocument rootDocument = XDocument(“... path ...”);解析结果完全一样。然后会有什么区别? – Turo

+0

好吧,也许他们解析相同,但我看到有一个区别。加载时使用XDocument时,我可以一步一步来。谢谢! – Turo