2013-04-18 82 views
-3

我有一個這樣的XML格式..XML負載與特定的過濾器

<ROOT> 
    <bookstore> 
     <Name>XXXXXX</BUNIT> 
    </bookstore> 
    <book> 
     <ID>000000000000001001</ID> 
     <title>Everyday Italian</title> 
     <author>Giada De Laurentiis</author> 
     <year>2005</year> 
     <price>30.00</price>   
    </book> 
    <book> 
     <ID>000000000000001002</ID> 
     <title>Everyday Italian</title> 
     <author>Giada De Laurentiis</author> 
     <year>2005</year> 
     <price>30.00</price>   
    </book> 
    <book> 
     <ID>000000000000001003</ID> 
     <title>Everyday Italian</title> 
     <author>Giada De Laurentiis</author> 
     <year>2005</year> 
     <price>30.00</price>   
    </book> 
    <book> 
     <ID>000000000000001004</ID> 
     <title>Everyday Italian</title> 
     <author>Giada De Laurentiis</author> 
     <year>2005</year> 
     <price>30.00</price>   
    </book> 
</ROOT> 

現在我想加載具有「ID」一書的只有一個節點不循環。 我已經嘗試了一些這這樣的.. 我們將得到書(第一項ID = 000000000000001001)的完全節點與下面的線

_nodeList = objxml.SelectSingleNode("//book/") 

,但我會給ID進行過濾,像下面的代碼。

_nodeList = objxml.SelectSingleNode("//book/ID['000000000000001001']") 

並且我需要具有該特定ID的完整書籍節點。

+1

你在你的XML中有錯誤,你沒有關閉''和什麼''? – DGibbs

+0

這是' XXXXXX'是個問題。 – Neolisk

回答

4

如果我正確地理解了這個問題,你想要通過子元素ID的值來選擇一個書元素?

如果這是你可以用一個非常簡單的LINQ查詢通過ID返回書節點的情況下(假設你已經先糾正你的XML):

var book = from n in xml.Descendants("ROOT").Elements("book") 
         where n.Element("ID").Value == "000000000000001001" 
         select n; 

然後,您可以項目的值,以匿名類型而投的查詢列表枚舉結果:

var book = (from n in xml.Descendants("ROOT").Elements("book") 
      where n.Element("ID").Value == "000000000000001001" 
      select new 
      { 
       ID = (string)n.Element("ID").Value, 
       Title = (string)n.Element("title").Value, 
       Author = (string)n.Element("author").Value, 
       Year = (string)n.Element("year").Value, 
       Price = (string)n.Element("price").Value 
      }).ToList(); 

哪位能給輸出,如:

enter image description here

1
var book = onjxml.SelectSingleNode("//ROOT/book[ID='000000000000001003']") 
+0

+1不過,你並不需要ROOT,而是用雙斜槓。 –