tags:

views:

111

answers:

2

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>
A: 

You can use CDATA and/or escape the HTML entities i.e. < becomes < etc.

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

Brian Agnew
+1  A: 

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.
tvanfosson