Are you just looking to select the node, or are you trying to actually
delete all other child nodes from the XML document. I suppose your post's
title suggests the latter.
You can select the node with a simple XPath expression, such as:
SelectSingleNode("//people/person[@name='tom']");
In order to remove all other children, you first need a reference to the
parent node. Assume you have a reference to the node in your example, called
peopleNode. You could do something like this:
int index = 0;
while (index < peopleNode.ChildNodes.Count)
{
if
(!peopleNode.ChildNodes[index].Attributes["name"].InnerText.Equals("tom");
peopleNode.RemoveChild(peopleNode.ChildNodes[index]);
else
index++;
}
You could easily replace the string literal "tom" with a variable as needed.
A few things to note:
- You cannot use a foreach loop since you are modifying the child node
collection inside the loop
- Thie code assumes that each child of peopleNode does have an attribute
called 'name' (otherwise you get a null reference exception)
- This code will loop through all children even after the one you're looking
for has been found. So there's room for optimization.
- String.Equals() is case-sensitive
--
Kai Brinkmann [MSFT]
Please do not send e-mail directly to this alias. This alias is for
newsgroup purposes only.
This posting is provided "AS IS" with no warranties, and confers no rights.
"daz_oldham" <Da**************@gmail.com> wrote in message
news:11**********************@j55g2000cwa.googlegr oups.com...
Hi everyone
An easy one I think, I am just not too sure of the best way of going
about this.
I have the following XmlNode as an example:
<people group="33" status="334kdnsfins435" value"x">
<person id="1" name="tom" />
<person id="2" name="sue" />
<person id="3" name="jim" />
<person id="4" name="bob" />
</people>
If I wanted to chop this down to just select tom i.e.:
<people group="33" status="334kdnsfins435" value"x">
<person id="1" name="tom" />
</people>
How would I do this - I can't quite fathom out the technique to do it.
Many thanks
Darren