2010-01-09 80 views
0

任何人都知道爲什麼這個XPath表達式"catzero/@id"不工作在這個xml問題閱讀的XElement屬性

document = XDocument.Load("file.xml"); 
var product = document.XPathSelectElements("//product", nameSpaceResolver).First(); 
var category = ((IEnumerable) product.XPathEvaluate("catzero/@id")).Cast<XAttribute>().first().value; //catezero/@id is null 
+0

請給出一些示例代碼並解釋發生了什麼 - 「不工作」不是很具描述性。 – 2010-01-09 13:51:07

+1

好吧好吧.. – h3n 2010-01-12 01:16:29

回答

1

XPath和LINQ到XML(XEelement)通常不匹配 - LINQ到XML使用它自己的方式來遍歷XML文檔。

在你的情況,你可以這樣做:

XDocument doc = XDocument.Load("http://www.quillarts.com/Test/Feed2.xml"); 

foreach(XElement xe in doc.Descendants("product")) 
{ 
    if(xe.Element("catzero") != null) 
    { 
     var attr = xe.Element("catzero").Attribute("id"); 

     if(attr != null && attr.Value == "20") 
     { 
      string elementValue = xe.Value; 
     } 
    } 
} 

我不從你的問題知道你想要什麼用這些元素做的和/或屬性 - 先走一步,做你需要做的事情。

1

寫它:

var product = document.XPathSelectElements("//product", nameSpaceResolver).First(); 
IEnumerable at = (IEnumerable)product.XPathEvaluate("catzero/@id"); 
var category = at.Cast<XAttribute>().First<XAttribute>().Value; 

如果你期望類的價值爲20。

1

它工作正常,我(固定FFirst()正常工作對我來說,VValue ,並傳遞一個null命名空間解析器),給出類別「20」。你期望有什麼不同嗎?如果是這樣,爲什麼?

同樣:

string category = document.Descendants("product").First() 
      .Elements("catzero").Attributes("id").First().Value; 

給出 「20」。