views:

615

answers:

4

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

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
A: 

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

Kb
A: 

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.

marc_s
A: 

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.

tyranid
A: 

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".

Marc Gravell