异常:XPath 表达式的计算结果为意外类型 System.Xml.Linq.XAttribute

Exception: The XPath expression evaluated to unexpected type System.Xml.Linq.XAttribute

我有一个 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 很好(尽管您可能希望它更 selective),但您必须调整评估它的方式...

XPathSelectElement(),顾名思义,应该只用于select个元素。

XPathEvaluate()更通用,可以用于属性。你可以枚举结果,或者抓取第一个:

var type = ((IEnumerable<object>)doc.XPathEvaluate("//Employee/Address/@Type"))
                                    .OfType<XAttribute>()
                                    .Single()
                                    .Value;

扩展 kjhughes 的回答,我倾向于为此创建一个 XElement class 扩展,以便我可以简单地调用 element.XPathSelectAttribute(),这使我的调用代码看起来更清晰.

public static class XElementExtensions
{
    public static XAttribute XPathSelectAttribute(this XElement element, string xPath)
    {
        return ((IEnumerable<object>)element.XPathEvaluate(xPath)).OfType<XAttribute>().First();
    }
}

另一种选择是:

var addresses = doc.XPathSelectElements("//Employee/Address"));
foreach(var address in addresses) {
    var addrType = address.Attribute("Type").Value;
}