473,804 Members | 3,705 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to tell if XmlNode is part of document tree

I have a container of XmlNodes. Some of them have been removed from
the document, some haven't. Is there an easy way to tell which are
which?

I suppose
bool IsPartOfTree(Xm lNode node)
{
while (node.ParentNod e != null) { node = ParentNode; }
return node == node.OwnerDocum ent;
}
would work, but it doesn't seem elegant.

Jan 23 '07 #1
7 2408
ma**********@ya hoo.co.uk wrote:
bool IsPartOfTree(Xm lNode node)
{
while (node.ParentNod e != null) { node = ParentNode; }
Should be
while (node.ParentNod e != null) { node = node.ParentNode ; }
I guess.
return node == node.OwnerDocum ent;
}
would work, but it doesn't seem elegant.
I don't think there is any method exposed that you could use so that
walk of the ParentNode hierarchy is not too bad.

If you don't want to use the loop you can use XPath e.g.

public static bool IsPartOfDocumen tTree (XmlNode node) {
return node.SelectSing leNode(@"ancest or::node()") ==
node.OwnerDocum ent;
}

--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Jan 23 '07 #2
Martin Honnen wrote:
ma**********@ya hoo.co.uk wrote:
bool IsPartOfTree(Xm lNode node)
{
while (node.ParentNod e != null) { node = node.ParentNode ; }
[snip correction - thanks!]
return node == node.OwnerDocum ent;
}
would work, but it doesn't seem elegant.

I don't think there is any method exposed that you could use so that
walk of the ParentNode hierarchy is not too bad.
Thanks. Sigh. (I suppose there isn't much that an API could do, other
than duplicate the loop).
If you don't want to use the loop you can use XPath e.g.

public static bool IsPartOfDocumen tTree (XmlNode node) {
return node.SelectSing leNode(@"ancest or::node()") ==
node.OwnerDocum ent;
}
Hmm. That seems like a sledgehammer to crack a nut. It also feels
hairy applying XPath to something that isn't (part of) a full document.

(On a different topic - I really dislike the way that
SelectNodes/SelectSingleNod e ignores the axis ordering. I think I
would make the XPath expression:
"ancestor::node ()[last()]"
which ought to accurately select the top of the tree.)

Jan 23 '07 #3
Why are you walking up the parent tree to look for the OwnerDocument? All
descendant nodes, not just the root, reference the parent document. For
instance, the following (assuming my source document had enough children to
return nodes from the XPath) would output the owning document's ToString for
each node:
foreach (XmlNode node in
myDocument.Sele ctNodes("//*[1]/*[1]/*"))
{
System.Diagnost ics.Debug.Write Line(node.Owner Document);
}
Jan 23 '07 #4
Keith Patrick wrote:
Why are you walking up the parent tree to look for the OwnerDocument?
Because he needs to find out whether walking up the parent hierarchy he
finds the OwnerDocument as an ancestor or not to check whether the node
he started with is included in the tree rooted by the OwnerDocument or
in an orphan subtree detached from the OwnerDocument.
--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Jan 23 '07 #5
On Jan 23, 2:18 pm, martinfro...@ya hoo.co.uk wrote:
I have a container of XmlNodes. Some of them have been removed from
the document, some haven't. Is there an easy way to tell which are
which?

I suppose
bool IsPartOfTree(Xm lNode node)
{
while (node.ParentNod e != null) { node = ParentNode; }
return node == node.OwnerDocum ent;
}
would work, but it doesn't seem elegant.
Oops. There are in fact TWO problems with the above code. Firstly, as
Martin Nonnen points out below, it should be:
node = node.ParentNode ;
secondly, the OwnerDocument property of the document node returns null.
So the final test should be:
return (node.NodeType == XmlNodeType.Doc ument);

So, in case somebody wants the full code, it should be:
public static bool IsPartOfDocumen tTree (XmlNode node)
{
while (node.ParentNod e != null)
{
node = node.ParentNode ;
}
return (node.NodeType == XmlNodeType.Doc ument);
}

(Note: The above has still not been compiled, let alone tested!)

Jan 24 '07 #6
I've never had a detached subtree still retain its reference to the original
document, so that's what I'm not seeing. Is he saying that when RemoveNode
is called, the doc reference remains?

Jan 24 '07 #7
Using the Kaysian method for intersection of node-sets the intersection is
non-empty if and only if:
count($ns1[count(.|$ns2) = count($ns2)]) 0

We can use this to tell whether two nodes belong to the same document, by
defining the two node-sets as the sets of ancestors of each of the given
nodes:

Therefore, two nodes belong to the same document if and only if:
count($node1/ancestor::node( )[count(.|$node2/ancestor::node( )) =
count($node2/ancestor::node( )) ]) 0

To answer your specific question, represent the document by the document
node (or by the top element) in the above XPath expression.

This was tested successfully with the XPath Visualizer and it is confirmed
that the above expression returns 'true' only in the case when the two nodes
belong to the same XML document

Cheers,
Dimitre Novatchev

<ma**********@y ahoo.co.ukwrote in message
news:11******** **************@ q2g2000cwa.goog legroups.com...
>I have a container of XmlNodes. Some of them have been removed from
the document, some haven't. Is there an easy way to tell which are
which?

I suppose
bool IsPartOfTree(Xm lNode node)
{
while (node.ParentNod e != null) { node = ParentNode; }
return node == node.OwnerDocum ent;
}
would work, but it doesn't seem elegant.

Jan 25 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1337
by: Michael Hutchinson | last post by:
When an XmlNode method returns an XmlNode, such as a child, is this generated on-the-fly or is it the actual component of the internal tree structure? If the parent is moved in the tree, will the pointer remain valid? I have looked at as much of the structure as I can using .NET Reflector and I think it will, but I want to be sure. I 'm planning to add XmlNodes to the Tag property of TreeNodes in a TreeView to be able to persist changes...
4
4967
by: Rune | last post by:
I have two queries that appear to be exactly the same, but one of them returns null while the other one returns a valid result! Can anyone provide an explanation to why this is so? Below is an nunit test that exposes the problem. I have run the test under both the 1.0 and 1.1 framework with the same result. public void XPathBooks() { XmlDocument smallDoc = new XmlDocument();
1
1281
by: Owen Blacker | last post by:
An awkward question. In a CMS-like environment, I have a list of items that is generated on the serverside using an XmlDocument to throw together XHTML tags (mainly because it's substantially easier than using a Repeater, but the why is a moot point as the project doesn't have the budget for me to change that). Now I have a requirement to add a new list item at the end of each list that is an "Add new item" form. It's very easy for...
5
5101
by: Paul | last post by:
Here I have the definition of an XmlNode which is a property (PayPreference) on my Customer class containing an enum describing how the customer will pay. <PayPerference xsi:type="a4:Customer+CustomerPayOptions" xmlns:a4="http://schemas.microsoft.com/clr/nsassem/OsfDomain.Resources.Stage/OsfDomain%2C%20Version%3D1.0.0.1%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">cash</PayPerference> I now want to add this XmlNode to a different...
5
2144
by: Mahesh Devjibhai Dhola | last post by:
Hi All, I want to make a custom class in c#, which extends System.Xml.XmlNode class of BCL. Now in custom class, I have implement abstract methods of XmlNode class also. Now when I am trying to run the class it gives an error that "System.Xml.XmlNode.XmlNode() is inaccessible due to its protection level". This error comes because XmlNode has not any public constructor. I found XmlNode has two constructor but both are private or friend...
0
1309
by: Philip Wagenaar | last post by:
I have an XML file that will contain the data of a binary file in MIME encoding. My application receiver the XML file with the location of the binary file: <REQUEST> <IMPORT> <DOCUMENT> <FIELD> <DATA>c:\myfile.dat</DATA> </FIELD>
1
18213
by: Marc | last post by:
Hi! I'm working with a C# client that calls a php web service. I've created a wrapper to call the service using .NET wsdl tool (adding a web reference). The call to the server works fine, it is serialized correctly, and the server returns a response (I've captured the response and it's correct!) but when the .NET deserialize this response, it throws the exception "System.InvalidOperationException: There is an error in XML
7
15318
by: Sharon | last post by:
How can I get the full XML path (as string) of a specific XmlNode ? -- Thanks Sharon
0
1204
by: =?Utf-8?B?ZGF2aWQ=?= | last post by:
When I create a tree view control from XML document, I use XmlNode.Name in the node list iteration. But sometime, it is supposed that it got the element name. But sometimes it got the element name and first attribute together. For eaxmple, I use the following iteration code after creating the root from DOM.DocumentElement.Name. ----- private void AddNode2(XmlNode inXmlNode, TreeNode inTreeNode) { XmlNode xNode;
0
10323
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10311
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10074
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9138
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6847
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5516
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5647
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3813
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2988
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.