Advertisement
fredrikmork

Remove XML attribute from XmlNode

May 11th, 2011
2,722
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.08 KB | None | 0 0
  1. /*
  2.  
  3. Code sample for answering a comment on this StackOverflow answer:
  4. http://stackoverflow.com/questions/875136/how-to-remove-an-xmlnode-from-xmlnodelist/875159#875159
  5.  
  6. */
  7. using System;
  8. using System.Xml;
  9.  
  10. namespace ConsoleApplication1
  11. {
  12.  
  13.     class Program
  14.     {
  15.         private const string XmlData =
  16.             @"<root><child id=""1"">content 1</child><child id =""2"" additionalStuff=""more stuff here"">content 2</child></root>";
  17.  
  18.         public static void Main()
  19.         {
  20.             var xmlDoc = new XmlDocument();
  21.             xmlDoc.LoadXml(XmlData);
  22.  
  23.             // select all nodes containing an 'additionalStuff' attribute
  24.             XmlNodeList nodes = xmlDoc.SelectNodes("//child[@additionalStuff]");
  25.             foreach (XmlNode node in nodes)            
  26.             {
  27.                 // remove the attribute
  28.                 node.Attributes.RemoveNamedItem("additionalStuff");
  29.             }
  30.  
  31.             // xmlDoc.Save(fileName);
  32.            
  33.             // display the resulting xml
  34.             Console.WriteLine(xmlDoc.OuterXml);
  35.         }
  36.  
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement