C#解析XML文件 [英] C# Parsing XML File

查看:81
本文介绍了C#解析XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在堆栈溢出时浏览了几个线程,但找不到答案.我有一个如下所示的xml文件设置:

I looked through a few thread here on stack overflow and I cannot find the answer. I have an xml file setup like the following:

<entry id="1" type="a">
    <name>string 1</name>
    <description>any description</description>
</entry>
<entry id="2" type="b">
    <name>string 2</name>
    <description>any description #2</description>
</entry>

我需要选择所有"entry"标签,然后返回该条目的ID,Type,内部名称和描述标签.我该如何使用C#?

I need to select all "entry" tags and return the ID, the Type, the inner name and description tags of the entry. How can I do so with C#?

谢谢

推荐答案

请记住,您的xml文件应具有单个根节点.这是使用Linq解析为Xml:

Keep in mind, that your xml file should have single root node. Here is parsing with Linq to Xml:

var xdoc = XDocument.Load(path_to_xml);
var entries = from e in xdoc.Descendants("entry")
              select new {
                 Id = (int)e.Attribute("id"),
                 Type = (string)e.Attribute("type"),
                 Name = (string)e.Element("name"),
                 Description = (string)e.Element("description")
              };

查询将返回与每个入口元素相对应的匿名对象序列(具有属性ID,Type,Name和Description).

Query will return sequence of anonymous objects corresponding to each entry element (with properties Id, Type, Name, and Description).

这篇关于C#解析XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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