通过c#获取xml元素childNode和属性值 [英] get xml Element childNode and attribute values through c#

查看:245
本文介绍了通过c#获取xml元素childNode和属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我有一个带有嵌套xml元素的xml架构,以下是其中的一小部分

I am having a xml schema with nested xml elements and following is the small piece of that

<aa>
<id extension="xx" root="56" />
<name>demo</name>
<telecom use="EC" value="tel:02073333333" />
</aa>

<bb>

  <value value="201505100000" />
</bb>
<cc>
  <value value="201805100000" />
</cc>



从这里我必须获得"aa tag"下的"name tag"的值,telecom标签的last属性(tel :)和"value tag"的属性值;(在bb标签和cc标签下找到)

from this i have to get the value of "name tag" under "aa tag", last attribute (tel:) of telecom tag, and attribute value of the "value tag" (which is found under bb tag and cc tag)

 i tried the following code, but it's not getting exactly what i am expecting.


xDoc.Descendants().Where(x => x.Name.LocalName.Equals("aa)
                        || x.Name.LocalName.Equals("telecom") && (x.FirstAttribute.Equals("EC")
                        || x.Name.LocalName.Equals("bb)
                        || x.Name.LocalName.Equals("cc))


please provide me the solution regarding this.

推荐答案

使用System添加'。 Xml.XPath'并试试这个:

Add ‘using System.Xml.XPath’ and try this:


string name = xDoc.XPathSelectElement(
" // AA / name" )?。值;


字符串 tel = xDoc.XPathSelectElement(
" // aa / telecom" ; )?。属性(
" value" )?。Value ;


字符串 bb = xDoc.XPathSelectElement(
" // bb / value" ; )?。属性(
" value" )?。Value ;


字符串 cc = xDoc.XPathSelectElement(
" // cc / value" ; )?。属性(
" value" )?。Value ;

 

样本文件:


<? xml
版本 = " 1.0 "
编码 = " utf-8 "
?>

<?xml version="1.0" encoding="utf-8" ?>


< 数据 >


 
<
aa >


   
<
id
扩展名 = " xx "
= " 56 "
/>

    <id extension="xx" root="56" />


   
<
名称 > 演示 < / 名称 >

    <name>demo</name>


   
<
电信
使用 = " EC "
= " 电话:02073333333 "
/>

    <telecom use="EC" value="tel:02073333333" />


 
< /
aa >


 
<
bb >


   
<

= " 201505100000 "
/>

    <value value="201505100000" />


 
< /
bb >


 
<
cc >


   
<

= " 201805100000 "
/>

    <value value="201805100000" />


 
< /
cc >


< / 数据 >

 

< span lang ="EN-GB"> 

如果文件中有更多此类元素,请提供更多详细信息。


这篇关于通过c#获取xml元素childNode和属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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