Click here to Skip to main content
15,914,222 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi guys,

i have a question. i have an xml file like:

<Group>
<1>Text1</1>
<1>text2</1>
</Group>

i want delete a <1> where element is text1 .

thanks in advance
Posted

Hi
check this code for your requirement.

C#
XmlTextReader reader = new XmlTextReader(Server.MapPath("~/SomeFiles") + "/" + "XMLFile4.xml");
reader.WhitespaceHandling = WhitespaceHandling.None;

XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(reader);
XmlNodeList xmlnodeli = xmldoc.SelectNodes("Group/1");
XmlNode  xmlnodeli1 = xmldoc.SelectSingleNode("Group");
XmlNode xn = null;
if (xmlnodeli.Count > 0)
{
      //you 've to check each and every node value if it has more than two nodes
    if (xmlnodeli[1].InnerText == "Test1")
    {
        xn = xmlnodeli[1];
    }
}
xmlnodeli1.RemoveChild(xn);
reader.Close();
xmldoc.Save(Server.MapPath("~/SomeFiles") + "/" + "XMLFile4change.xml");


I hope you understood What I did.

All the Best
 
Share this answer
 
You should check your Xml format first.I'm not sure in XML tag can give only number or not.I will give you sample of my XML and Delete node.

XML
XML
<?xml version="1.0" encoding="utf-8"?>
<Group>
  <G1>Text1</G1>
  <G1>Text2</G1>
</Group>


Sample C# code
XmlTextReader reader = new XmlTextReader(Server.MapPath("~/XMLFile") + "/" + "Test.xml");
 reader.WhitespaceHandling = WhitespaceHandling.None;

 XmlDocument xmldoc = new XmlDocument();
 xmldoc.Load(reader);
 XmlNodeList xmlnodelist = xmldoc.SelectNodes("Group/G1");
 XmlNode xmlnode = xmldoc.SelectSingleNode("Group");
 XmlNode xn = null;
 if (xmlnodelist.Count > 0)
 {
     //you 've to check each and every node value if it has more than two nodes
     for (int i = 0; i < xmlnodelist.Count; i++)
     {
         if (xmlnodelist[i].InnerText == "Text1")
         {
             xn = xmlnodelist[1];
         }
     }

 }
 if (xn != null)
 {
     xmlnode.RemoveChild(xn);
 }
 reader.Close();
 xmldoc.Save(Server.MapPath("~/XMLFile") + "/" + "Test.xml"");
 
Share this answer
 
Hi,

You can use system.Xml.Linq to perform same task in two lines as shown below:

C#
var elements = XElement.Parse("<group><g1>Text1</g1><g1>Text2</g1><g1>Text3</g1></group>").Elements();

//OR
//var elements = XElement.Load("samplefilePath").Elements();

elements.Where(ele => ele.Value == "Text1").Remove();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900