尝试使用 LINQ XML 将以下 XML 文件(可以更改)读入对象到 VAR。
<?xml version='1.0'?>
<config>
<report>
<name>Adjustment Report</name>
<extension>pdf</extension>
<filetype>adobe_pdf</Filetype>
<field name="total" type="currency" />
<field name="adjust" type="currency" />
<field name="monthly" type="currency" />
<output>
<format>Excel</format>
<AutoFormat>True</AutoFormat>
</output>
<reportstart>adjustment report</reportstart>
<reportend></reportend>
<linebegins>
<regex>(?<ssn>\d{3}-\d{2}-\d{4})</Regex>
</linebegins>
<regex>"(?<last>\s{0,1}[A-Z-'.]+\s{0,1}[A-Z-'.]+),(?<first>\s[A-Z-'.]+\s{0,1})(?<middle>[A-Z][.]|\s{0,1})"></Regex>
<regex>"(?<ssn>\d{3}-\d{2}-\d{4})"</Regex>
<regex>"(?<total>\$[,/d]+)(?<adjust>\$[,/d]+)(?<monthly>\$[,/d]+)"</Regex>
</report>
</config>
不起作用的是将多个元素读入对象。我只能读第一本。显然持有字段的对象需要是一个数组?这是我目前的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ElementDemo
{
class Program
{
static void Main(string[] args)
{
XElement xml = XElement.Load("C:\\TEMP\\test.xml");
var reports = from report in xml.Descendants("report")
where report.Element("name").Value.Contains("Adjustment Report")
select new
{
Name = report.Element("name").Value,
Extension = report.Element("extension").Value,
FileType = report.Element("filetype").Value,
// Fields : How is this done?
};
foreach(var obj in reports)
{
Console.WriteLine("Name: " + obj.Name );
};
Console.ReadLine();
}
}
}
提前致谢。
最佳答案
使用 Elements
方法获取所有 field
元素,然后调用 Select
将它们变成对象。
例如:
var reports = from report in xml.Descendants("report")
where report.Element("name").Value.Contains("Adjustment Report")
select new {
Name = report.Element("name").Value,
Extension = report.Element("extension").Value,
FileType = report.Element("filetype").Value,
Fields = report.Elements("field")
.Select(f => new {
Name = f.Attribute("name").Value,
Type = f.Attribute("type").Value
}).ToArray()
};
关于C# LINQ with XML,无法将同名的多个字段提取到对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1980263/