使用 C# 从 xml 读取子元素 [英] Read child elements using C# from xml

查看:23
本文介绍了使用 C# 从 xml 读取子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,使用 C# 列出的 xml 文件中的 ID 属性从子元素读取所有属性的最佳做法是什么.

Greeting, What is the best practice to read all attributes from a child elements by ID attributes using C# in xml file listed down.

谢谢,

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

  <Program ID="1" Name="CIS562" StartDate="9/8/2010 5:50:00 PM" EndDate="9/8/2010 9:15:00 PM" />

  <Program ID="2" Name="CIS532" StartDate="10/8/2010 5:50:00 PM" EndDate="10/8/2010 9:15:00 PM" />

  <Program ID="3" Name="ECE552" StartDate="6/8/2010 5:50:00 PM" EndDate="6/8/2010 9:15:00 PM" />

</WinDLN>

推荐答案

以下 LINQ 调用应该可以解决问题:

The following LINQ call should do the trick:

var attrs = 
  doc.Descendants("Program").First(prog =>
    prog.Attribute("ID").Value == "2").Attributes();

Descendants 方法为您提供 XML 文档中名为Program"的所有元素(任何位置).使用 First,您可以获得与某些指定谓词匹配的第一个(例如,ID"等于2").请注意,如果您想在没有这样的元素时获得 null,您可以使用 FirstOrDefault.最后,Attributes 为您提供元素所有属性的集合.

The Descendants method gives you all elements (anywhere) in the XML document that are named "Program". Using First, you can get the first one that matches some specified predicate (e.g. has "ID" equal to "2"). Note that you can use FirstOrDefault if you want to get null when there is no such element. Finally, Attributes gives you a collection of all attribtues of the element.

我认为,如果可以,最好使用 LINQ to XML - 在处理 XML 或其他数据源时,您将编写相同的代码,因此阅读和编写代码很容易(一旦您学习了 LINQ).

I think that using LINQ to XML if you can is preferrable - you'll write the same code when working with XML or other data sources, so reading and writing the code is easy (once you learn LINQ).

这篇关于使用 C# 从 xml 读取子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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