XmlNode.RemoveAll() removes all *child nodes* of the node (including
attributes) but *not* the node itself. Are you sure there is no sign of the
node in the saved XML file? I would expect the file to look like this after
your code runs:
<Catalog>
<File ID = "1">
<Customer>Me</Customer>
<Date>Today</Date>
.
.
.
</File>
<File />
</Catalog>
The empty <File /> node corresponds to <File ID="2"> with all attributes and
child nodes deleted.
Try replacing your delete statement with this:
nl.Item
.ParentNode.RemoveChild(nl.Item);
BTW, you could simplify your code somewhat using XPath expressions. Since
you know up front which node you would like to delete, there is really no
need to loop through all file nodes. You could simply do this:
XmlNode node = xml.SelectSingleNode("//File[@ID='2']");
node.ParentNode.RemoveChild(node);
The first line selects the first file node anywhere with an ID attribute
with value 2. The next line removes this node.
--
Kai Brinkmann [Microsoft]
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.
melanieab said:
Hi,
I'm deleting nodes in my xml file, and it does seem to work, but then when
I
later reload the file and make an xmlNodeList, the nodelist count still
includes the deleted nodes yet the file shows no sign of them. Here is
what
I have:
Example of my xml:
<Catalog>
<File ID = "1">
<Customer>Me</Customer>
<Date>Today</Date>
.
.
.
</File>
<File ID = "2">
.
.
.
</File>
and so on.
Here's how I've deleted it:
string cat = @"C:\Catalog.xml";
XmlDocument xml = new XmlDocument();
xml.Load(cat);
XmlNodeList nl = xml.GetElementsByTagName("File");
for (int i = 0; i < nl.Count; i++)
{
if (int.Parse(nl.Item(i).Attributes["ID"].Value) == 2)
{
nl.Item(i).RemoveAll();
xml.Save(cat);
}
} (I'm trying to delete File 2 as well as all it's children.)
So later, I want to load the data in the xml file and create a new
XmlNodeList.
I was getting errors so I checked the nl.Count.ToString() and it was still
the original number before deletion. But upon opening the xml file, there
is
no sign of the nodes I deleted.
Thanks again for any help!
Mel