Tuesday, May 3, 2011

How can I load a hashtable from an XML file?

I want to load all the name/value pairs into a hashtable from an XML file in C#.

Note, the 'value' part may contain HTML markup, so it has to somehow escape from that. Would this be done in code or should I use CDATA?

Example XML:

<root><node name="node1">value</node><node name="node1">value2</node><root>
From stackoverflow
  • You can use CDATA and/or escape the HTML entities i.e. < becomes < etc.

    See the remarkable specialist website http://escapehtmlforxml.com/ (!)

  • Yes, I would wrap any HTML in CDATA, then it would be trivial to select these into a Dictionary<string,string>.

        string xml = "<?xml version= '1.0'?><root><node name=\"node1\">value</node><node name=\"node2\">value2</node></root>";
        var doc = XDocument.Parse( xml );
        var dict = doc.Element("root")
                      .Elements( "node" )
                      .Select( e => new
                       {
                           Key = e.Attribute( "name" ).Value,
                           Value = e.Value
                       } )
                      .ToDictionary( k => k.Key, v => v.Value );
    
    tvanfosson : There were a couple of problems with my initial example -- that comes from writing code directly into the question instead of pre-testing it. This code should work though.

0 comments:

Post a Comment