General discussion

Locked

XPath Syntax question

By wlhs ·
I am looking for the syntax to select a node in an xmlDocument.

I want to select the <Template> node using selectSingleNode in the following xml snippet, where <Name>Template1</Name>.

<Templates>
<Template>
<Name>Template1</Name>
<Description>The first template</Description>
</Template>
<Template>
<Name>Template2</Name>
<Description>The second template</Description>
</Template>
</Templates>

This conversation is currently closed to new comments.

2 total posts (Page 1 of 1)  
| Thread display: Collapse - | Expand +

All Comments

Collapse -

by andreas.kamentz In reply to XPath Syntax question

As I assume, you're looking for some solution in C#. For such purpose I use a simple routine written by me, which is looking for the first node with a specified value "id" at the XPath address "idPath" in the given node list (e.g. children of the parent node). The XPath address must be relative to the top of each node in the list (you are looking for a node with a value at location specified _within_ this node). If the value "id" has some special character (defined as a constant "NOT") prepended to it, then the function is looking for the first node which is NOT having the value "id" at the address "idPath".

private XmlNode NodeInList (XmlNodeList Nds, string idPath, string id)
{
id = id.Trim();
foreach (XmlNode nd in Nds)
{
bool neg;
if (neg = id.StartsWith(NOT)) id = id.Substring(NOT.Length);
XmlNode pathnd = nd.SelectSingleNode(idPath);
if (pathnd != null && (!neg && pathnd.InnerText.Trim()==id || neg && pathnd.InnerText.Trim()!=id)) return nd;
}
return null;
}

In your case the code would be like this, assuming your "Templates" Node belongs to an xmlDocument "tmplDoc":

XmlNode tmpl1Nd = NodeInList(tmplDoc.DocumentElement.SelectSingleNode("Templates").ChildNodes,
"Name", "Template1");

Collapse -

by andreas.kamentz In reply to XPath Syntax question

Sorry, I submitted my "NodeInList" idea just a few minutes ago, but now I realized that the most simple way is just to use an XPath string with a node test condition:

string tmpl1Path = "Templates/Template[Name='Template1']";

Then you get the node you are looking for simply as

xmlNode tmpl1Nd = tmplDoc.DocumentElement.SelectSingleNode(tmpl1Path);

Looking for node in a list may be useful in some other special cases, the "NodeInList" subroutine can be also extended to look for a node basing on more then one condition, both positive and negative.

Back to Web Development Forum
2 total posts (Page 1 of 1)  

Related Discussions

Related Forums