簡體   English   中英

C#如何將xml轉換為字典以獲取一個屬性和多個元素的值

[英]c# how to convert xml to dictionary to get values of one attribute and multiple elments

我需要將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>

您的幫助將不勝感激。 非常感謝!

我認為您可以做一些澄清,但這可以達到預期的效果,盡管您還不清楚,但假設Vendor屬性名稱應該是Vendor部分的Key。

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>

  • 鑰匙 :BankRed
  • :dfas16549464 1,12
  • 鑰匙 :BankBlue
  • :foo bar

但是,我認為您采用了錯誤的方法。 更好的主意是創建一個自定義類型的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列表,如下所示:

在此處輸入圖片說明

數據現在更容易使用。

我已經編寫了代碼並對其進行了測試。 我希望這就是您所需要的,盡管您不清楚我為什么需要它的問題:使用字典的Entity類:

公共類Entity {私有字符串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);
     }

嘗試使用以下代碼:

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM