简体   繁体   中英

Convert xml contents to a key value pair in C#

Is there any way to convert an xml to key-value pair in an easier way without iterating through every nodes and elements

My XML structure is similar to this

<root>  
  <StandardValues>    
    <ButtonYES alias="customname value">Ja</ButtonYES>
    <ButtonNO>Nei</ButtonNO>
  </StandardValues>
  <Page1>
    <Key_Head>2011 Applications</Key_Head>
    <Key_Title>Title from 2011</Key_Title>
    <Key_Param1>Parameter value</Key_Param1>
  </Page1>
   <Page2>
    <Page_Head>2011 Applications</Page_Head>
    <page_Title>Title from 2011</page_Title>
    <CustomParam1>Parameter value</CustomParam1>
  </Page2>
</root> 

As it's clear that the ElementNode names and sub xml node names are not uniform in nature, it can be any names [xml tags[ and it can be any number of subitems

The idea of XML conversion is to enable translation for an application where final object is a Dic

What is the best way to do conversion from XML to key-value pair list

I tried this

         var maping = doc.Descendants("Page1")
              .Elements()
              .ToDictionary(d => (string)d.Name.LocalName,
                            d => (string)d.Value);

But its returning for only one set page1 Can we make it for all children's of root

Using this approach i am able to read it to a class with 3 properties

  var maping = doc.Descendants("Page1")
              .Elements().Select(d => new
                      {
                          Attribute = (string)d.Name.LocalName,
                          Value = d.Value, // equal to id you are searching for
                          Key = (d.Attribute("alias") != null) ? d.Attribute("alias").Value : ""
                      }).ToList();

        foreach (var s in maping)
        {
            string ss = string.Format("{0} -  {1} && {2}", s.Key, s.Value, s.Attribute);
        }

Not sure if you already tried this,

var doc = XDocument.Load(yourXML);
var maping = doc.Root.Elements()
                   .ToDictionary(a => (string)a.Attribute("key"),
                                 a => (string)a.Attribute("replaceWith"));

There are other ways too, I found this more fast.

Recursive LINQ query will help you to form hierarchical structure,

public class AwesomeXml
{
    public static void Main()
    {
        string xml = @"<root>  
                    <StandardValues>    
                    <ButtonYES>Ja</ButtonYES>
                    <ButtonNO>Nei</ButtonNO>
                    </StandardValues>
                    <Page1>
                    <Key_Head>2011 Applications</Key_Head>
                    <Key_Title>Title from 2011</Key_Title>
                    <Key_Param1>Parameter value</Key_Param1>
                    </Page1>
                    <Page2>
                    <Page_Head>2011 Applications</Page_Head>
                    <page_Title>Title from 2011</page_Title>
                    <CustomParam1>Parameter value</CustomParam1>
                    </Page2>
                    </root>";       

        var doc = XDocument.Parse(xml);
        var result = ConvertXmlToDic(doc.Root);
        Console.Read();
    }

    private static object ConvertXmlToDic(XElement element)
    {            
        var result = element.Elements().
            Select(
                e => new { Key = e.Name,
                           Value = (e.Descendants().Count() == 0) ? e.Value : ConvertXmlToDic(e)
                }
            ).ToDictionary(e => e.Key, e => e.Value);
        return result;
    }        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM