如何在c#中访问xml文件中的元素 [英] How can I access to elemnts inside an xml file in c#

查看:177
本文介绍了如何在c#中访问xml文件中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

xml文件是这样的:

例如我想访问Child1里面的元素

xml file is like this:
for example I want to access elemnts inside of Child1

<main>
 <child1>
    <part1>
       <a></a>
       
    </part1>
    <part1>
       <a></a>
       
    </part1>
 </child1>
 <child2>
    <part2>
       <c></c>
       <d></d>
    </part2>
 </child2>
 <child3>
    <part3>
    </part3>
 </child3>
</main>





之前的xml以下我写了下面的代码,那没关系。



before for below xml I wrote below code and that was OK.

<child1>
   <part1>
      <a></a>
      
   </part1>
   <part1>
      <a></a>
      
   </part1>
</child1>




var doc = XElement.Load(txtRecivePath.Text);
                var ms = doc.Elements("part1").ToList();
                fields = ms.Select(s => new Class_PersonelInfo()
                {
                    prsnlCod = s.Element("a").Value;
                }

推荐答案

使用 doc。 Descendants (child1); 而不是。
Use doc.Descendants("child1"); instead.


你使用 s.Element(a),但是没有 a 元素直接在你的child1标签中。 part1 a 标签>标签。



要访问 a -tags,您可以使用。后代

You use s.Element("a"), but there are no a elements directly in your child1 tag. There are only a tags in your part1 tag.

To access the a-tags, you can use s.Descendants:
var doc = XElement.Parse(xml);
var ms = doc.Elements("child1").ToList();
var allATags = ms.Select(s => s.Descendants(XName.Get("a")))
    .SelectMany(x => x)
    .ToList();



ms.Select 在此处返回XElements集合的集合。 SelectMany 将它们全部合并为一个, ToList 将其转换为列表。现在 allATags 包含所有 a -tags child1 -tags 。


ms.Select returns a collection of collections of XElements here. SelectMany merges them all into one, and ToList converts it to a list. Now allATags contains all a-tags within child1-tags.


试试这个...



Try this...

var xdoc= XElement.Parse(xml);
var app = from p in xdoc.Elements("a")
          select p;


这篇关于如何在c#中访问xml文件中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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