I’m trying to select nodes starting from nodes that are not root nodes of XML documents. The code the following:
foreach (XmlNode xmlIter in root.SelectNodes("/refentry/refsect1[@id='parameters']/variablelist/*")) {
Parameter p = new Parameter();
xmlNode = xmlIter.SelectSingleNode("varlistentry/term/parameter");
p.Identifier = xmlNode.InnerText;
xmlNode = xmlIter.SelectSingleNode("varlistentry/listitem");
p.Documentation = xmlNode.InnerText;
}
The XML document (here is only a snippet) is the following:
<refsect1 id="parameters"><title>Parameters</title>
<variablelist>
<varlistentry>
<term><parameter>pipeline</parameter></term>
<listitem>
<para>
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>program</parameter></term>
<listitem>
<para>
</para>
</listitem>
</varlistentry>
</variablelist>
</refsect1>
But the above code doesn’t work: the xmlNode variable is always null… What’s wrong?
The leading “/” means “start at the root of the document”. Try just:
(If you’re using .NET 3.5 or later I’d personally use LINQ to XML instead – I find it easier to use than XPath, but that’s a different matter. I can provide the equivalent LINQ to XML code if you want.)
EDIT: Got it. Your
[stuff]/variablelist/*query is already going into thevarlistentrynode – you’re then trying to find anothervarlistentrynode beneath it. If you select all thevarlistentryelements instead, you only need to find theterm/parameterandlistitemelements under thatvarlistentry.This works:
Mind you, it would probably still be worth validating that
xmlNodeis non-null before using it.