gpt4 book ai didi

C# LINQ with XML,无法将同名的多个字段提取到对象中

转载 作者:数据小太阳 更新时间:2023-10-29 02:20:09 26 4
gpt4 key购买 nike

尝试使用 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>(?&lt;ssn&gt;\d{3}-\d{2}-\d{4})</Regex>
</linebegins>
<regex>"(?&lt;last&gt;\s{0,1}[A-Z-'.]+\s{0,1}[A-Z-'.]+),(?&lt;first&gt;\s[A-Z-'.]+\s{0,1})(?&lt;middle&gt;[A-Z][.]|\s{0,1})"></Regex>
<regex>"(?&lt;ssn&gt;\d{3}-\d{2}-\d{4})"</Regex>
<regex>"(?&lt;total&gt;\$[,/d]+)(?&lt;adjust&gt;\$[,/d]+)(?&lt;monthly&gt;\$[,/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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com