开发者

Problem Reading XElement Attribute

Anyone knows why this xpath expression "catzero/@id" is not working on this xml

document = XDocument.Load("file.x开发者_运维技巧ml");
var product = document.XPathSelectElements("//product", nameSpaceResolver).First();
var category = ((IEnumerable) product.XPathEvaluate("catzero/@id")).Cast<XAttribute>().first().value; //catezero/@id is null


XPath and Linq-to-XML (XEelement) don't typically match - Linq-to-XML uses it's own approach to traversing XML documents.

In your case, you'd be able to do something like:

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;
        }
    }
}

I don't know from your question what you want to do with these elements and/or attributes - just go ahead and do whatever you need to do.


Writing it as:

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

Works fine for me if you expect the value of category to be 20.


It works fine for me (fixing the F in First(), the V in Value, and passing a null namespace-resolver), giving the category "20". Do you expect something different? If so, what and why?

Likewise:

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

gives "20".


Are you entering Xpath expression into Xelement()?
To use Xpath you should try http://msdn.microsoft.com/en-us/library/system.web.ui.templatecontrol.xpathselect.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜