tags:

views:

50

answers:

3

Is there a special XML element for name/value property pairs like the following, something that I can leverage in C# code?

   <Properties>
        <Property>
            <Name>xyz</Name>
            <Value>abc</Value>
        </Property>
    </Properties>
A: 

You could use attributes. Attributes are name-value pairs associated to tags like so:

<Tag xyz="abc">
    <!-- more XML tags -->
</Tag>
BranTheMan
+1  A: 

I dont know anything directly unless you use Serialization to do it for you.

I have found this form to be pretty useful, and fairly compact in most situations:

<properties>
   <property key="xyz">abc</property>
</properties>

Then iterate through them with something similar to:

Dictionary<string, string> properties = new Dictionary<string, string>()
foreach(XmlNode property in root.SelectNodes("properties/property") {
   string name = property.Attributes["key"].Value as string
   string value = property.InnerText;

   properties.add(name, value);
}
GrayWizardx
Could also be <property name="xyz" value="abc"/> if value isn't expected to be big...
Osama ALASSIRY
the problem with putting value in the tag itself is that you run into formatting issues. If you have a value of "this text is "quoted"", it gets problematic. Inside the node you can just do <property key=key"><![CDATA[Some pretty <complicated> Text? "yes"]]></property>
GrayWizardx
Couldn't you just html encode any input? Which you should do anyways if the input is coming from the web.
Abe Miessler
It depends, yes you could encode it, but that does pose its own problems (like making sure the consumer knows they need to unencode it, which may or may not be important). Also embedding it in the tag does not allow you to specify list/dictionary style values for your values. Using this method it is possible to have the value itself be a List<string> by having sub-nodes. if the sub-nodes have "key" attributes then it becomes a dictionary. The extension to that structure is quite trivial and can use recursion to deal with the parsing.
GrayWizardx
+1  A: 

XML and C# are completely different. You can parse any valid XML using C#. Could you describe what your end goal is in more detail?

Abe Miessler