By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,984 Members | 997 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,984 IT Pros & Developers. It's quick & easy.

delete nodes in XML

Shinobi
P: 7
I am trying to delete a node in xml. Nothing is worked correctly.
Here is XML
Expand|Select|Wrap|Line Numbers
  1. <cat>
  2.   <category>
  3.     <id>1</id>
  4.     <name>Architecture</name>
  5.   </category>
  6.   <category>
  7.     <id>2</id>
  8.     <name>Education</name>
  9.   </category>
  10.  
I tried this code. But not worked.
Expand|Select|Wrap|Line Numbers
  1. XmlDocument xdoc = new XmlDocument();
  2.         xdoc.Load(Server.MapPath("main.xml"));
  3.         XmlNodeList nodes = xdoc.GetElementsByTagName("category");
  4.         foreach (XmlNode node in nodes)
  5.         {
  6.  
  7.             if (node["id"].InnerText == id)
  8.             {
  9.                 node.ParentNode.ParentNode.RemoveChild(node.ParentNode);
  10.             }
  11.  
  12.         }
Please help me.

Thanks.
Dec 9 '08 #1
Share this Question
Share on Google+
3 Replies


nukefusion
Expert 100+
P: 221
You look like you've got too many ParentNode's in that last bit. Try:

Expand|Select|Wrap|Line Numbers
  1. XmlDocument xdoc = new XmlDocument();
  2. xdoc.Load(Server.MapPath("main.xml"));
  3. XmlNodeList nodes = xdoc.GetElementsByTagName("category");
  4. foreach (XmlNode node in nodes)
  5. {
  6.     if (node["id"].InnerText == "1")
  7.     {
  8.         node.ParentNode.RemoveChild(node);
  9.     }
  10. }
  11.  
A slightly better implementation might be to use XPath to find the target node, rather than looping through lots of nodes. Something like:

Expand|Select|Wrap|Line Numbers
  1.           XmlDocument xdoc = new XmlDocument();
  2.             xdoc.Load(Server.MapPath("main.xml"));
  3.             XmlNode childToDelete = xdoc.SelectSingleNode("/cat/category[id=\"1\"]");
  4.             childToDelete.ParentNode.RemoveChild(childToDelete);
  5.  
Dec 9 '08 #2

Shinobi
P: 7
Thanks. Yhank u so much
Dec 10 '08 #3

Expert 100+
P: 750
PRR
@Shinobi
In addition to what nukefusion explained... you could also use a dataset...Dataset Read Write XML
Dec 11 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.