在c#中使用Linq-to-XML解析XML的示例
本文关键字:XML 解析 Linq-to-XML | 更新日期: 2023-09-27 17:57:29
昨晚我提出了一个关于如何解析重复的XML结构的问题。XML有两个重复的级别,第二个级别包含我需要存储在其他地方的元素。
这个问题被标记为重复,并指向一个公认的答案,基本上是"将Linq用于XML"。
虽然我很感激这个答案,但我的问题的底部指出,我试图了解如何使用LINQ to XML,但不知道如何访问二级数据。
关于如何使用LINQ to XML或任何其他方法来获取XML文档中的信息并能够在其中循环,是否有任何易于理解的示例或教程?
我以前用Perl做过这件事,它基本上吸收了XML,并创建了一个可以迭代的大对象。
链接到原始问题:用C Sharp 解析XML
他们说"熟能生巧"。有时候,做一件事多次是最好的学习方法。使用linq方法"ToList()",类似于下面的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input =
"<Data>" +
"<Report>" +
"<Machine name='"hostA'">" +
"<MachineInfo location='"LA'">" +
"<function name='"run'">Late</function>" +
"<function name='"status'">Complete</function>" +
"<function name='"date'">2015-06-14</function>" +
"</MachineInfo>" +
"<RepItem name='"1488'" direction='"NS'">" +
"<Desc>None Found</Desc>" +
"<Status Int='"A12'">Uplink</Status>" +
"</RepItem>" +
"<RepItem name='"1489'" direction='"S'">" +
"<Desc>31Ghz Ant at 285ft.</Desc>" +
"<Status Int='"D5'">Active</Status>" +
"</RepItem>" +
"<RepItem name='"1438'" direction='"W'">" +
"<Desc>West N. Oc. Backup</Desc>" +
"<Status Int='"A11'">Disabled</Status>" +
"</RepItem>" +
"<RepItem name='"1141'" direction='"SE'">" +
"<Desc>MDT Co.</Desc>" +
"<Status Int='"B7'">Active</Status>" +
"</RepItem>" +
"</Machine>" +
"<Machine name='"hostB'">" +
"<MachineInfo location='"E. LA'">" +
"<function name='"run'">Late</function>" +
"<function name='"status'">Complete</function>" +
"<function name='"date'">2015-06-14</function>" +
"</MachineInfo>" +
"<RepItem name='"1488'" direction='"NS'">" +
"<Desc>None Found</Desc>" +
"<Status Int='"A12'">Down</Status>" +
"</RepItem>" +
"<RepItem name='"1489'" direction='"S'">" +
"<Desc>31Ghz Ant at 285ft.</Desc>" +
"<Status Int='"D5'">Active</Status>" +
"</RepItem>" +
"<RepItem name='"1438'" direction='"W'">" +
"<Desc>West N. Oc. Backup</Desc>" +
"<Status Int='"A11'">Disabled</Status>" +
"</RepItem>" +
"<RepItem name='"1141'" direction='"SE'">" +
"<Desc>MDT Co.</Desc>" +
"<Status Int='"B7'">Active</Status>" +
"</RepItem>" +
"</Machine>" +
"</Report>" +
"</Data>";
XDocument doc = XDocument.Parse(input);
var results = doc.Descendants("Machine")
.Select(x => new {
name = x.Attribute("name").Value,
info = new {
machineInfo = x.Element("MachineInfo").Attribute("location").Value,
functions = x.Element("MachineInfo").Elements("function").Select(y => y.Value).ToList()
},
repItems = x.Elements("RepItem")
.Select(y => new {
name = y.Attribute("name").Value,
direction = y.Attribute("direction").Value,
description = y.Element("Desc").Value,
status = y.Element("Status").Value,
index = y.Element("Status").Attribute("Int").Value
}).ToList()
})
.ToList();
}
}
}