Problema di lettura XElement attributo
-
19-09-2019 - |
Domanda
Chiunque sa perché questo espressioni XPath "catzero/@id"
non sta lavorando su questo 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
Soluzione
Si sta entrando un'espressione XPath in XElement ()?
Per usare XPath si dovrebbe provare a http: // msdn.microsoft.com/en-us/library/system.web.ui.templatecontrol.xpathselect.aspx
Altri suggerimenti
XPath e LINQ-to-XML (XEelement) in genere non corrispondono - Linq-to-XML utilizza è proprio approccio ad attraversare i documenti XML
.Nel tuo caso, devi essere in grado di fare qualcosa di simile:
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;
}
}
}
Non so dalla tua domanda che cosa si vuole fare con questi elementi e / o attributi -. Basta andare avanti e fare quello che devi fare
Scrittura come:
var product = document.XPathSelectElements("//product", nameSpaceResolver).First();
IEnumerable at = (IEnumerable)product.XPathEvaluate("catzero/@id");
var category = at.Cast<XAttribute>().First<XAttribute>().Value;
funziona bene per me se si prevede che il valore di categoria di essere 20.
Funziona bene per me (che fissa il F
nel First()
, il V
in Value
, e il superamento di un null
namespace-resolver), dando la categoria "20". Si aspetta qualcosa di diverso? Se sì, quali e perché?
Allo stesso modo:
string category = document.Descendants("product").First()
.Elements("catzero").Attributes("id").First().Value;
dà "20".