我认为您可以澄清一下,但假设 Vendor 属性名称应该是 Vendor 部分的键,这可以达到预期的效果,尽管您还不清楚
XDocument xml = XDocument.Load("path to your xml file");
var dict = xml.Descendants("Vendors")
.Elements()
.ToDictionary(r => r.Attribute("name").Value, r => r.Value);
假设一个 XML 结构:
<root>
<Vendors>
<Vendor name="BankRed">
<CustRef>dfas16549464</CustRef>
<InvP> 1, 12</InvP>
</Vendor>
</Vendors>
<Vendors>
<Vendor name="BankBlue">
<CustRef>foo</CustRef>
<InvP>bar</InvP>
</Vendor>
</Vendors>
</root>
你会得到一个Dictionary<string, string>
有两个元素的,看起来像: -
- 键:银行红
- 值:dfas16549464 1、12
- 键:BankBlue
- 价值观:富吧
但是,我认为您采取了错误的方法。一个更好的主意是创建一个自定义类型Vendor
来存储这些信息,例如:
public class Vendor
{
public Vendor()
{ }
public string CustRef { get; set; }
public string VendorName { get; set; }
public string InvP { get; set; }
}
查询将变为:
var query = (from n in xml.Descendants("Vendors")
select new Vendor()
{
VendorName = n.Element("Vendor").Attribute("name").Value,
CustRef = n.Descendants("Vendor").Select(x => x.Element("CustRef").Value).SingleOrDefault(),
InvP = n.Descendants("Vendor").Select(x => x.Element("InvP").Value).SingleOrDefault()
}).ToList();
这将为您提供Vendor
如下所示的 s 列表:
![在此处输入图像描述](https://i.stack.imgur.com/mZEMw.png)
数据现在更容易处理。