2015-02-09 35 views
0

我想在C#中的作者節點下獲取電子郵件的值。但是什麼都沒有來。我的代碼是=移動到linq的節點值到XML C#?

XDocument xDoc = XDocument.Parse("myxml"); 
var foos = from xelem in xDoc.Descendants("author") 
       select xelem.Element("email").Value; 

XML,我現在用的就是 -

<?xml version="1.0" encoding="UTF-8"?> 
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:batch="http://schemas.google.com/gdata/batch" 

xmlns:gContact="http://schemas.google.com/contact/2008" xmlns:gd="http://schemas.google.com/g/2005" 

xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"> 
<id>[email protected]</id> 
<updated>2015-02-09T04:03:31.220Z</updated> 
<category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/contact/2008#contact"/> 
<title type="text">Yogesh Adhikari's Contacts</title> 
<link rel="alternate" type="text/html" href="https://www.google.com/"/> 
<link rel="next" type="application/atom+xml" href="https://www.google.com/m8/feeds/contacts/yogeshcs2003%40gmail.com/full?max- 

results=1&amp;start-index=2"/> 
<author> 
    <name>Yogesh Adhikari</name> 
    <email>[email protected]</email> 
</author> 
<generator version="1.0" uri="http://www.google.com/m8/feeds">Contacts</generator> 
<openSearch:totalResults>3099</openSearch:totalResults> 
<openSearch:startIndex>1</openSearch:startIndex> 
<openSearch:itemsPerPage>1</openSearch:itemsPerPage> 
</feed> 

有人能說出什麼是錯的? 謝謝

+0

你應該也發佈XML以及你試圖解析的問題。 – 2015-02-09 04:53:53

+0

元素名稱位於'http:// www.w3.org/2005/Atom'命名空間中。 – 2015-02-09 04:58:52

+0

我正在嘗試使用linq來到節點「作者」,但失敗? – yogihosting 2015-02-09 05:02:12

回答

2

您需要在獲取子代時指定命名空間和名稱。

XDocument xDoc = XDocument.Parse("myxml"); 
string ns = xDoc.Root.Name.Namespace; 

var foos = from xelem in xDoc.Descendants(ns + "author") 
      select xelem.Element(ns + "email").Value; 

或者,您也可以通過獲取枚舉超過所有後代,然後通過過濾LocalName找到你的節點。如果email是隻在author在你的架構中的一個節點,你也可避免鑽從author節點下的不必要的步驟,而直接找到你的email節點:

var foos = xdoc.Descendants().Where(e => e.Name.LocalName == "email"); 
+0

第二行是'xDocument'是什麼? – yogihosting 2015-02-09 05:19:48

+0

@yogihosting對不起,應該是'xDoc'。 – 2015-02-09 05:20:14

+0

感謝第一個代碼無法正常工作,但lambda表達式的最後一行代碼完美工作。非常感謝 – yogihosting 2015-02-09 05:35:01

2
XDocument xDoc = XDocument.Load("myxml.xml"); 
var foos = xDoc.Descendants().Where(e => e.Name.LocalName == "email"); 
Console.WriteLine(foos.FirstOrDefault().Value); 

使用Load方法,如果你引用xml文件,否則解析應該沒問題。如果不使用特定路徑,還要確保xml與您的二進制文件夾一起。

+0

完美的作品。謝謝。 – yogihosting 2015-02-09 05:33:57

+0

不錯的一個Jenish .. – 2015-02-09 05:44:09