3
試圖使用LINQ XML將以下XML文件(可以更改爲)讀入到一個VAR中。帶有XML的C#LINQ無法將多個具有相同名稱的字段提取到對象中
<?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();
}
}
}
在此先感謝。