Search code examples
.netxmlsystem.xml

Attribute vs Child node


I'm new to XML and am wondering when I should use a Attribute, and when I should use a Child node.

My guess is I should use an attribute if I want to use that field like an index.

For example, I'm currently (for purposes of getting my head around XML) making a program to keep logs, so I have 2 main fields "datetime" and "text" I think maybe "datetime" should be an attribute


Solution

  • The main thing about attributes is that they are unique per element. This means that an attribute cannot be declared with the same name multiple times so its usually a good idea to use them for storing things that should not have more than one value. Also because of the syntax and the fact that they are declared in the element tag I find it usefull to use them for things that intimiately related to that element like ids.

    Another rule of thumb is that I would not use an attribute for things that have ver long values as it makes for a messy read. Like in the case of your log text.

    For your specifc question yes I would use an attribute for the timestamp and place the text between the element tags.

    One more piece of advice about XML especially since you are just starting, if you are not doing it already, to use the XML objects provided by the language to create and write XML. It may be more verbose then writing the XML out to a string manually, but it will save you from adding illegal characters in the middle by accident.

    For example if you are a logging text that has a < in it creating something like:

    <Root> <Log datatime="sometime"> this would break the XML < right there. </Log> <Root>

    This XML file would be broken. The XML objects would escape illegal values automatically to look like

    <Root> <Log datatime="sometime"> this would break the XML &lt; right there. </Log> </Root>

    I hope this helps and good luck.