加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 异常:XPath表达式计算为意外类型System.Xml.Linq.XAttrib

发布时间:2020-12-15 08:41:50 所属栏目:百科 来源:网络整理
导读:我有一个像下面这样的 XML文件: Employees Employee Id="ABC001" NamePrasad 1/Name Mobile9986730630/Mobile Address Type="Perminant" CityCity1/City CountryIndia/Country /Address Address Type="Temporary" CityCity2/City CountryIndia/Country /Add
我有一个像下面这样的 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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读