异常:XPath表达式的计算结果为意外类型System.Xml.Linq.XAttribute [英] Exception: The XPath expression evaluated to unexpected type System.Xml.Linq.XAttribute

查看:62
本文介绍了异常:XPath表达式的计算结果为意外类型System.Xml.Linq.XAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的XML文件:

I've an XML file like below:

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

现在我要获取所有的地址类型.

Now I want get all Address Type's.

我像下面那样使用XPath尝试,但出现异常.

I tried like below using XPath and I'm getting exception.

var xPathString = @"//Employee/Address/@Type";
doc.XPathSelectElements(xPathString); // doc is XDocument.Load("xml file Path")

异常:XPath表达式评估为意外类型System.Xml.Linq.XAttribute.

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

我的XPath是否有问题?

Is there any issue with my XPath?

推荐答案

您的XPath很好(尽管您可能希望它更具选择性),但是您必须调整评估方式...

Your XPath is fine (although you might want it to be more selective), but you have to adjust how you evaluate it...

XPathSelectElement() ,顾名思义,它只能用于选择元素.

XPathSelectElement(), as its name implies, should only be used to select elements.

XPathEvaluate() 还是更多常规,可用于属性.您可以列举结果,也可以抓取第一个:

XPathEvaluate() is more general and can be used for attributes. You can enumerate over the results, or grab the first:

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

这篇关于异常:XPath表达式的计算结果为意外类型System.Xml.Linq.XAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆