XPath for robust message handling

Consider the xml message below

<document xmlns="http://www.valid.nl/2015/test">
    <page id="1">
      <text bold="true">This is my text</text>
    <page id="2">
      <text>Hello world</text>
    <page id="3">
      <text bold="true">Next information</text>

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;
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}",

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?


W3Schools XPath Tutorial
Ignore namespace answer on stackoverflow

About erictummers

Working in a DevOps team is the best thing that happened to me. 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.