2015-11-02 87 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