XPath for robust message handling

Consider the xml message below

<document xmlns="http://www.valid.nl/2015/test">
  <meta>
    <documentid>1234</documentid>
    <documentlocation>c:\temp\data.xml</documentlocation>
  </meta>
  <pages>
    <page id="1">
      <text bold="true">This is my text</text>
    </page>
    <page id="2">
      <text>Hello world</text>
    </page>
    <page id="3">
      <text bold="true">Next information</text>
    </page>
  </pages>
</document>

Mapping this to a class would make it tightly coupled. Any change to the message would mean an update to the class. We expect some minor changes to the XSD / XML message but only want to recompile on “real” impact like extra (needed) information. Changing the naming of the root node or grouping nodes should not result in a new deployment.

We plan to do this by querying the message with XPath. That searches for the information in the xml and does not need a complete mapping of the message to a class. Code says more than a thousand words.

var doc = new XmlDocument();
using(var reader = new XmlTextReader(path)) {
    // needed to ignore the namespace
    reader.Namespaces = false;
    doc.Load(reader);
}
var docid = doc.SelectSingleNode("//documentid");
var doclocation = doc.SelectSingleNode("//documentlocation");
var boldTexts = doc.SelectNodes("//text[@bold='true']");

Console.WriteLine("DocumentId: {0}", docid.InnerText);
Console.WriteLine("DocumentLocation: {0}", doclocation.InnerText);
foreach(XmlNode boldText in boldTexts) {
    Console.WriteLine("Found bold text: {0} on Page: {1}",
        boldText.InnerText,
        boldText.ParentNode.Attributes["id"].Value);
}

Changing the tags <document>, <meta>, <pages>, <page> or adding things like <headings> has no impact and the code would output the same.

What do you think?

References

W3Schools XPath Tutorial
Ignore namespace answer on stackoverflow

About erictummers

My work as a recruited developer changes almost every month. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s