Connecting Tech Pros Worldwide Help | Site Map

Issue selecting the correct nodes

DeveloperX
Guest
 
Posts: n/a
#1: Oct 24 '08
Hi, I should probably start with my XML as it makes it easier to
explain the problem.


<?xml version="1.0" encoding="utf-8" ?>
<aa note="top level">

<b1 note="b1">
<c1 note="b1 c1">
<d1 note="b1 c1 d1" />
</c1>
<c2 note="b1 c2">
<d1 note="b1 c2 d1" />
</c2>
</b1>

<b2>
<c1 note="b2 c1">
<d1 note="b2 c1 d1" />
</c1>
<c2 note="b2 c2">
<d1 note="b2 c2 d1" />
</c2>
</b2>

<b3>
<c1 note="b3 c1">
<d1 note="b3 c1 d1" />
</c1>
</b3>

</aa>


Essentially I wish to select one b node, pass that node to another
method and then carry out operations on its sub nodes.

Here's some test code, the problem is in the last line where it tries
to assign list3.

XmlDocument doc = new XmlDocument();
doc.Load("c:\\a.xml");
XmlNode node = doc.SelectSingleNode(@"/aa/b1");
XmlDocument doc2 = new XmlDocument();
doc2.LoadXml(node.OuterXml);
XmlNodeList list = doc2.SelectNodes(@"/b1/c1/*"); //works, 1 node
XmlNodeList list2 = node.SelectNodes(@"/aa/b1/c1/*"); //works, 1 node
XmlNodeList list3 = node.SelectNodes(@"/b1/c1/*"); //want to work, 0
nodes :(

My problem is, the method passed the b node will not know from where
it came, and I would prefer to keep it that way. It just seems a bit
counter intuitive to me to select on a node and it not to be the root.

Anyway, any help would be appreciated.

Thanks
Martin Honnen
Guest
 
Posts: n/a
#2: Oct 24 '08

re: Issue selecting the correct nodes


DeveloperX wrote:
Quote:
XmlDocument doc = new XmlDocument();
doc.Load("c:\\a.xml");
XmlNode node = doc.SelectSingleNode(@"/aa/b1");
XmlDocument doc2 = new XmlDocument();
doc2.LoadXml(node.OuterXml);
XmlNodeList list = doc2.SelectNodes(@"/b1/c1/*"); //works, 1 node
XmlNodeList list2 = node.SelectNodes(@"/aa/b1/c1/*"); //works, 1 node
XmlNodeList list3 = node.SelectNodes(@"/b1/c1/*"); //want to work, 0
nodes :(
>
My problem is, the method passed the b node will not know from where
it came, and I would prefer to keep it that way. It just seems a bit
counter intuitive to me to select on a node and it not to be the root.
Well if SelectNodes or SelectSingleNode would consider the node they are
called on the root node then you could never access any parent or
ancestor nodes.
So if you want to use XPath and SelectNodes/SelectSingleNode then you
have to live with '/' selecting the root node (the document node in the
DOM model). So you need to use
XmlNodeList list3 = node.SelectNodes(@"c1/*");

--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Closed Thread