在C#程序中,我需要从一个XML结构中获取属性值。我可以直接作为XElement访问此XML结构,并使用简单的xpath字符串获取属性。但是,使用XPathEvaluate大多数情况下会返回空数组。(是的,有时候会返回属性,但大部分情况下不会......对于完全相同的XElement和xpath字符串......)
然而,如果我先将XML转换为字符串,然后重新解析为XDocument,则总是能够获取属性。有人可以解释一下这种行为吗?(使用.NET 3.5)
以下是通常返回一个空IEnumerable的代码:
以下是通常返回一个空IEnumerable的代码:
string xpath = "/exampleRoot/exampleSection[@name='test']/@value";
XElement myXelement = RetrieveXElement();
((IEnumerable)myXElement.XPathEvaluate(xpath)).Cast<XAttribute>().FirstOrDefault().Value;
总是有效的代码(我得到我的属性值):
string xpath = "/exampleRoot/exampleSection[@name='test']/@value";
string myXml = RetrieveXElement().ToString();
XDocument xdoc = XDocument.Parse(myXml);
((IEnumerable)xdoc.XPathEvaluate(xpath)).Cast<XAttribute>().FirstOrDefault().Value;
使用测试 XML:
<exampleRoot>
<exampleSection name="test" value="2" />
<exampleSection name="test2" value="2" />
</exampleRoot>
根据周围环境的建议,我在一个测试程序中进行了一些“干燥测试”,使用相同的xml结构(txtbxXml和txtbxXpath代表上述xml和xpath表达式):
// 1. XDocument Trial:
((IEnumerable)XDocument.Parse(txtbxXml.Text).XPathEvaluate(txtbxXPath.Text)).Cast<XAttribute>().FirstOrDefault().Value.ToString();
// 2. XElement trial:
((IEnumerable)XElement.Parse(txtbxXml.Text).XPathEvaluate(txtbxXPath.Text)).Cast<XAttribute>().FirstOrDefault().Value.ToString();
// 3. XElement originating from other root:
((IEnumerable)(new XElement("otherRoot", XElement.Parse(txtbxXml.Text)).Element("exampleRoot")).XPathEvaluate(txtbxXPath.Text)).Cast<XAttribute>().FirstOrDefault().Value.ToString();
结果:情况1和3产生了正确的结果,而情况2抛出了一个nullref异常。如果情况3失败而情况2成功,那么对我来说可能有些意义,但现在我不明白了...
RetrieveXElement()
是做什么的? - AnirudhaSystem.Xml.Linq
中使用 XPath? - Jodrell