Solved

How Do I Delete An XML Node And Its Children With C# Without Leaving An Empty Element Behind?

Posted on 2008-06-18
4
289 Views
Last Modified: 2011-04-14
Hello.
I am trying to delete an XML node and all its children without leaving behind an empy element.  Below is the xml before the delete:

<?xml version="1.0" encoding="utf-8"?>
<WorkTeams>
  <WorkTeam Name="BlueTeam">
    <HomeBase>Los Angeles</HomeBase>
    <Vehicles>35</Vehicles>
    <VehicleMfgs>
      <VehicleMfg>Toyota</VehicleMfg>
      <VehicleMfg>Nissan</VehicleMfg>
      <VehicleMfg>Volvo</VehicleMfg>
    </VehicleMfgs>
  </WorkTeam>
  <WorkTeam Name="RedTeam">
    <HomeBase>San Diego</HomeBase>
    <Vehicles>20</Vehicles>
    <VehicleMfgs>
      <VehicleMfg>Ford</VehicleMfg>
      <VehicleMfg>Dodge</VehicleMfg>
      <VehicleMfg>Suzuki</VehicleMfg>
    </VehicleMfgs>
  </WorkTeam>
</WorkTeams>

I am trying to delete the node for   <WorkTeam Name="RedTeam"> and all its children.  I have written the following C# code to do this but the problem with it is that it leaves behind an empy node:

            XmlDocument anXmlDoc = new XmlDocument();
            const string XmlFilePath = "c:\\workteams.xml";
            const string XmlFileModifiedPath = "c:\\workteams2.xml";

            anXmlDoc.Load(XmlFilePath);

            XmlNodeList anXmlNodeListOfWorkTeam = anXmlDoc.GetElementsByTagName("WorkTeam");

            XmlNode anXMLNodeForWorkTeam = anXmlNodeListOfWorkTeam[0].SelectSingleNode("/WorkTeams/WorkTeam[@Name='RedTeam']");

            if (anXMLNodeForWorkTeam != null)
            {  
                anXMLNodeForWorkTeam.RemoveAll();
                anXmlDoc.Save(XmlFileModifiedPath);
            }

After running the above C# program the XML ends up looking as follows:

<?xml version="1.0" encoding="utf-8"?>
<WorkTeams>
  <WorkTeam Name="BlueTeam">
    <HomeBase>Los Angeles</HomeBase>
    <Vehicles>35</Vehicles>
    <VehicleMfgs>
      <VehicleMfg>Toyota</VehicleMfg>
      <VehicleMfg>Nissan</VehicleMfg>
      <VehicleMfg>Volvo</VehicleMfg>
    </VehicleMfgs>
  </WorkTeam>
  <WorkTeam>
  </WorkTeam>
</WorkTeams>

At the bottom I am left with an empty node showing as
<WorkTeam>
</WorkTeam>

How can I perform the delete without ending up with this empty node?  A code example solving the above example is what I am looking for.  Thanks in advance
0
Comment
Question by:zonkerman
  • 2
4 Comments
 
LVL 16

Expert Comment

by:burakiewicz
ID: 21813396
try this
if (anXMLNodeForWorkTeam != null)
            {  
anXmlNodeListOfWorkTeam[0].RemoveChild(anXMLNodeForWorkTeam);
                anXmlDoc.Save(XmlFileModifiedPath);
            }
0
 
LVL 12

Accepted Solution

by:
jandromeda earned 500 total points
ID: 21813595
Use this code.
XmlDocument anXmlDoc = new XmlDocument();

            const string XmlFilePath = "c:\\workteams.xml";

            const string XmlFileModifiedPath = "c:\\workteams2.xml";
 

            anXmlDoc.Load(XmlFilePath);
 

XmlNode removeNode = anXmlDoc.SelectSingleNode("//WorkTeam[@Name='RedTeam']");

			anXmlDoc.DocumentElement.RemoveChild(removeNode);

Open in new window

0
 
LVL 1

Author Comment

by:zonkerman
ID: 21814688
Hello Jandromeda.
Your code does all nodes related to RedTeam properly.  Thanks!  Looks like you might have forgotten to add the save statement but you did plan to implement it because of the XMLFileModifiedPath variable so I simply added that one statement

anXmlDoc.Save(XmlFileModifiedPath);

to the end of your sample as follows:

        private void button2_Click(object sender, EventArgs e)
        {
            XmlDocument anXmlDoc = new XmlDocument();
            const string XmlFilePath = "c:\\workteams.xml";
            const string XmlFileModifiedPath = "c:\\workteams2.xml";

            anXmlDoc.Load(XmlFilePath);

            XmlNode removeNode = anXmlDoc.SelectSingleNode("//WorkTeam[@Name='RedTeam']");
            anXmlDoc.DocumentElement.RemoveChild(removeNode);
            anXmlDoc.Save(XmlFileModifiedPath);
        }
0
 
LVL 12

Expert Comment

by:jandromeda
ID: 21819025
I intentionally did not included it as you already know how to save an Xml document. I'm really sorry if that cause you any inconveniences.
Happy coding! :)
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

I was working on a PowerPoint add-in the other day and a client asked me "can you implement a feature which processes a chart when it's pasted into a slide from another deck?". It got me wondering how to hook into built-in ribbon events in Office.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now