2012-07-31 70 views
0

我有以下XML結構:的Xml搜索節點問題

<html xmlns ="http://www.w3.org/1999/xhtml" > 
<head> 
    . . 
</head> 
<body> 
    <div id="1"></div> 
    <div id="2"></div> 
</body> 
</html> 

我使用LINQ爲XML ID = 「2」 來訪問DIV。我在XDocument中加載了文檔:

XDocument ndoc = XDcoument.load(path); 
    XElement n = new XElement("name","value"); 
    XNamespace xn = "http://www.w3.org/1999/xhtml"; 

ndoc.Descendants(xn + "div").Single(p => p.Attribute("id").Value == "1").Add(n); 

          OR 

ndoc.Descendants("div").Single(p => p.Attribute("id").Value == "1").Add(n); 

我試過兩種情況,每種情況下都有一個異常序列不包含任何元素。這裏有什麼問題?

+0

你說你正在尋找'與ID的div =「2」'但在你的代碼中,你正在檢查'... Value ==「1」'那你想要哪個? – 2012-07-31 17:48:37

回答

0

你可以給這個Xml Library一掄,它應該很容易得到它:

XElement root = XElement.Load(path); 
XElement div = root.XPathElement("//div[@id={0}]", 1); 
if(null != div) // which it shouldn't be 
    div.Add(n); 
0

這應該工作

XNamespace xn = XNamespace.Get("http://www.w3.org/1999/xhtml"); 
ndoc.Descendants(xn + "div").Single(p => p.Attribute("id").Value == "1").Add(n); 
0

這將工作

XDocument ndoc =XDcoument.load(path); 
XElement n = new XElement("name", "value"); 
XNamespace xn = "http://www.w3.org/1999/xhtml"; 

var item = ndoc.Descendants(xn + "div").FirstOrDefault(p => p.Attribute("id").Value == "1"); 
if(item!=null) 
    item.Add(n); 

使用Single方法,如果你確信將有隻有一個元素出自你的表情。請注意,Descendants()將爲您提供來自任何子級別(兒童,大孩子等)的匹配條件的所有元素。請注意,Descendants()將爲您提供來自任何子級別的匹配條件的所有元素。 )

Elements()方法將只給你立即(直接)的孩子。

所以仔細使用它。

+1

難道你不認爲真正的問題不是例外,但沒有找到搜索到的元素?例外只是結果=) – 2012-07-31 15:43:00

+0

@OleksandrPshenychnyy:是的。這就是爲什麼我要在調用Add方法之前進行空檢查。在Descendants方法中有名稱空間會得到你的元素,如果它存在。 – Shyju 2012-07-31 15:46:56

0

對我來說,你的榜樣(有點修改)正常工作:

var xml = @"<html xmlns ='http://www.w3.org/1999/xhtml' > 
<head> 
</head> 
<body> 
    <div id='1'></div> 
    <div id='2'></div> 
</body> 
</html>"; 
      XDocument xd = XDocument.Parse(xml); 

      XElement n = new XElement("name", "value"); 
      XNamespace xn = "http://www.w3.org/1999/xhtml"; 

      xd.Descendants(xn + "div").Single(p => p.Attribute("id").Value == "1").Add(n); 

      Console.WriteLine(xd); 

輸出

<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head></head> 
    <body> 
    <div id="1"> 
     <name xmlns="">value</name> 
    </div> 
    <div id="2"></div> 
    </body> 
</html> 

所以,我真的不明白你的問題。請檢查您複製正確=)