XPath

2023-02-02 XML XPath Selectors C# XmlDocument XmlNode SelectNodes SelectSingleNode

The XPath is expression language to address nodes of XML trees. It uses compact, non-XML syntax and is used by various DOM libraries, XSL templates and other tools.

Consider following XML:

<entries>
  <entry path="path/item1" driver="A664" crc="272190171" type="uint8" />
  <entry path="path/dir/item2" driver="A664" crc="1164726718" type="uint8" />
  <entry path="path/dir/item3" driver="ADN" crc="1985960093" type="uint8" />
  <entry path="path/item4" driver="ADN" crc="4022757236" type="uint8" />
</entries>

Loading of such thing can be done via something like

XmlDocument doc = new XmlDocument();
doc.Load(LayoutPath);

foreach (XmlNode entry in doc.SelectNodes("//entry"))
{
    string path = entry.Attributes["path"].Value;
    string type = entry.Attributes["type"].Value;
    string crc = entry.Attributes["crc"].Value;
    string driver = entry.Attributes["driver"].Value;

    allEntries.Add(new DataEntry(path, drv, crc, type));
}

The methods SelectNodes and SelectSingleNode accepts an XPath expression, former returns IEnumerable of matching nodes, latter returns first matching node.

Here are some useful examples of XPath expressions

XPath Meaning
//node <node> elements anywhere
//*[@title] all elements with title attribute
//tr[td[1][@class="td_background"]] table rows where first td has class td_background
//comment() all XML comments
/configuration/property[name="server"]/value/text() text of all configuration properties with name server