0

我需要将 xml 转换为字典。我以前从来没有这样做过。你能告诉我一个代码示例如何将此 xml 转换为字典以获取如下值:

Key: Vendor and Value: BankRed
Key: CustRef and Value: dfas16549464
Key: InvP and Value: 1, 12

这是xml:

<root>
    <Vendor name = "BankRed">
       <CustRef>dfas16549464</CustRef>
       <InvP> 1, 12</InvP>
    </Vendor>
</root>

您的帮助将不胜感激。非常感谢!

4

3 回答 3

1

我认为您可以澄清一下,但假设 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 列表:

在此处输入图像描述

数据现在更容易处理。

于 2013-07-09T09:12:20.270 回答
0

我已经编写了代码并对其进行了测试。我希望这就是您所需要的,尽管您的问题不清楚为什么需要它:用于字典使用的类实体:

公共类实体 { 私有字符串 CustRef; 私有字符串 InvP;

  public Entity(string custRef, string invP)
  {
     CustRef = custRef;
     InvP = invP;
  }
}

和转换代码:

     Dictionary<string, Entity> myTbl = new Dictionary<string, Entity>();
     XmlDocument doc = new XmlDocument();
     doc.Load(@"d:\meXml.xml");
     XmlNode root = doc.FirstChild;
     foreach (XmlNode childNode in root.ChildNodes)
     {
        myTbl[childNode.Attributes[0].Value] = new Entity(
           childNode.FirstChild.InnerText, 
           childNode.LastChild.InnerText);
     }
于 2013-07-09T08:11:47.973 回答
-3

尝试使用以下代码:

Dictionary<int, string> elements = xml.Elements(ns + "root")
        .Select(sp => new { 
                              CustRef = (string)(sp.Attribute("CustRef")), 
                              vendor = (string)(sp.Attribute("Vendor")) 
                          })
        .ToDictionary(sp => sp.CustRef, sp => sp.Vendor);
于 2013-07-09T08:01:34.223 回答