2014-03-24 122 views
0

我有一個由HTML標籤,如下圖所示下面的XML文件:LINQ的XML查詢沒有返回預期的結果

<?xml version="1.0" encoding="UTF-8"?> 

<html> 
<head> 
<title> 
title1 
</title> 
</head> 

<body> 
<fragment id="heading1"> 
<h1> 
Heading 1 
</h1> 
</fragment> 
<fragment id="heading2"> 
<h2> 
Heading 2 
</h2> 
</fragment> 
<fragment id="paragraph1"> 
<p> 
Paragraph 1 
</p> 
</fragment> 
</body>     
</html> 

我試圖提取所有片段ID和使用LINQ的XML顯示它們。查詢如下所示:

XDocument xelement = XDocument.Load("Path\\To\\XMLFile"); 
var name = from nm in xelement.Descendants("body") 
select nm.Element("fragment").Attribute("id").Value; 
Console.WriteLine(name); 

該查詢返回的輸出是:

標題1

但我想要的是:

標題1 heading2 1款

我在做什麼錯? 請諮詢。

謝謝

回答

1

我已經測試其工作正常選擇值!

XDocument po = XDocument.Load(@"XMLFile1.xml"); 
     IEnumerable<string> names = from id in po.Descendants("fragment").Attributes("id") select id.Value; 
      string str = string.Empty; 
      foreach (var el in names) 
      { 
       str += el;    
      } 
      System.Console.WriteLine(str); 
      Console.ReadKey(); 
+0

謝謝尼爾。但是你能解釋一下它不適用於XDocument嗎? – Anvith

+0

它適用於XDocument看到我更新的答案@Anvith – Neel

2

可以使用

IEnumerable<string> names = from id in xelement.Descendants("fragment").Attributes("id") select id.Value; 

IEnumerable<string> names = from frag in xelement.Descendants("fragment") select frag.Attribute("id").Value; 
+0

謝謝馬丁:) – Anvith