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