Sigh. Writing XML DOM code
I had to create a quick tool last week that had the simple task of parsing through an XML file and getting a set of atrributes from any node that had a specific value for a different attribute. This is vaguely the equivalent of writing down the license plate numbers of all pickups in a parking garage and ignoring the cars. Sounds simple, but it is always surprising to me how much code I have to write to work with the XML DOM in the .net framework.
Here's what I came up with:
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(txtConfigLocation.Text);
XmlNodeList myNodeList;
actionNodeList = xmlDoc.DocumentElement.SelectNodes("//myAction");
int i = 0;
XmlAttributeCollection attrColl;
foreach (XmlNode node in myNodeList)
{
attrColl = node.Attributes;
result[i] = attrColl.GetNamedItem("name").Value;
i++;
}
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.ToString(), "Error in GetActionListArray");
result = null;
}
return result ;
And I'm leaving out the code that sets the path to the Text file and the calling code as well.
That seems to be quite a bit of code just to get some string data out of a file. The trickiest part was the "//" in the SelectNodes command - Xpath needs this to know to search sub nodes. About 20 lines, depending on how you count them, seems like plenty to get this done.
Oh, and I also left out the logging I used to log the results from this.
I've read a little about Linq and how it can help here but I simply have not had time to learn that library. If there is a another small project like this that comes up maybe I can carve out some time to learn that and hopefully will need to write less code in the future.
Anyway, every time I write code using the DOM I always am amazed at how much code results, even in a simple case like this.
Questions, comments, concerns and criticisms always welcome,
John
Comments
- Anonymous
May 24, 2012
You can do something like //myAction/@name to directly select the attributes so that you don't have to go through the attribute collection to get to the value of the attribute. >getting a set of attributes from any node that had a specific value for a different attribute Xpath is actually very powerful. You can do //myAction[@category='X']/@name to get name attribute of myAction elements that have category attribute set to X, which sounds like what you wanted to do.