与XML C#LINQ,不能提取具有相同名称为对象多个字段 [英] C# LINQ with XML, cannot extract multiple fields with same name into object
本文介绍了与XML C#LINQ,不能提取具有相同名称为对象多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
试图读入一个对象下面的XML文件(可改变)到使用LINQ XML一个VAR。
Trying to read into an object the following XML file (can be changed) into a VAR using LINQ XML.
<?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>
什么是不工作的读取多个元素融入对象。我只能读取第一个。显然,持有该领域的对象必须是一个数组?这是我到目前为止的代码
What isn't working is reading multiple elements into the object. I can only read the first one. Obviously the Object that holds the field needs to be an array? This is the code I have so far.
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();
}
}
}
在此先感谢。
推荐答案
使用的 元素
方法来获取所有的字段的
元素,然后调用的 选择
使他们成为对象。
Use the Elements
method to get all of the field
elements, then call Select
to turn them into objects.
例如:
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()
};
这篇关于与XML C#LINQ,不能提取具有相同名称为对象多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文