我有一个如下所示的 XML 文件:
<Employees>
<Employee Id="ABC001">
<Name>Prasad 1</Name>
<Mobile>9986730630</Mobile>
<Address Type="Perminant">
<City>City1</City>
<Country>India</Country>
</Address>
<Address Type="Temporary">
<City>City2</City>
<Country>India</Country>
</Address>
</Employee>
现在我想获取所有地址类型。
我像下面这样使用 XPath 进行了尝试,但出现了异常。
var xPathString = @"//Employee/Address/@Type";
doc.XPathSelectElements(xPathString); // doc is XDocument.Load("xml file Path")
Exception: The XPath expression evaluated to unexpected type System.Xml.Linq.XAttribute.
我的 XPath 有问题吗?
最佳答案
您的 XPath 很好(尽管您可能希望它更具选择性),但您必须调整评估它的方式...
XPathSelectElement()
,顾名思义,应该只用于选择元素。
XPathEvaluate()
更通用,可用于属性。您可以枚举结果,或获取第一个:
var type = ((IEnumerable<object>)doc.XPathEvaluate("//Employee/Address/@Type"))
.OfType<XAttribute>()
.Single()
.Value;
关于c# - 异常 : The XPath expression evaluated to unexpected type System. Xml.Linq.XAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39360398/