2

we are thinking use xml file to store our error codes for our C# application. for the following two structures, which one is better?

<error>
<code>0x00000001</code>
<description>Error PIB: Clamp</description>
<reaction>Display</reaction>
</error>

or

<error code=0x00000001 >
<description>Error PIB: Clamp</description>
<reaction>Display</reaction>
</error>

or your better suggestion?

seems the second one save some space and easiler for lookup through it?

I need to get the description and reaction string by lookup the error code. do you have an effective way to lookup through file?

5YrsLaterDBA
  • 33,370
  • 43
  • 136
  • 210

2 Answers2

4

If you were after space-saving techniques, I would suggest not using XML in the first place :)

Personally I prefer the second approach over the first, but both will work. If this is really just for lookup, I'd suggest that when you load the file, you convert it to a Dictionary<String, ErrorInformation> or something similar. (You could make the key value a numeric type instead, but that would require parsing the value of course.)

LINQ to XML makes it really easy to do this sort of conversion:

XDocument xml = XDocument.Load("errorcodes.xml");
var dictionary = xml.Descendants("error")
                    .ToDictionary(element => (string) element.Attribute("code"),
                                  element => new ErrorInformation(
                                      (string) element.Element("description"),
                                      (string) element.Element("reaction")));
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • +1, xml != space-saving. For space saving, you could go with something like JSON objects. There is a lot less info stored in JSON compared to XML. Only, XML is a lot easier to deal with in the code. If space isn't that big of a deal, I really like the approach given here. It's very simple and understandable – joe_coolish Apr 12 '11 at 15:33
1

In general, if you want the code to describe the element, make it an attribute. If you want the code to be an element (meaning that the code will also require attributes or even sub information) make it a child.

In your code, option 2 is best IMO

joe_coolish
  • 7,201
  • 13
  • 64
  • 111