How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this: // instantiate XmlDocument and load XML from file XmlDocument doc = new XmlDocument(); doc.Load(@”D:\test.xml”); // get a list of nodes – in this case, I’m selecting all <AID> nodes under // the <GroupAIDs> node – change to suit your needs XmlNodeList aNodes = doc.SelectNodes(“/Equipment/DataCollections/GroupAIDs/AID”); // loop through all … Read more

Deciding on when to use XmlDocument vs XmlReader

I’ve generally looked at it not from a fastest perspective, but rather from a memory utilization perspective. All of the implementations have been fast enough for the usage scenarios I’ve used them in (typical enterprise integration). However, where I’ve fallen down, and sometimes spectacularly, is not taking into account the general size of the XML … Read more

XML Document to String

Assuming doc is your instance of org.w3c.dom.Document: TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, “yes”); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); String output = writer.getBuffer().toString().replaceAll(“\n|\r”, “”);

How to Select XML Nodes with XML Namespaces from an XmlDocument?

You have to declare the dc namespace prefix using an XmlNamespaceManager before you can use it in XPath expressions: XmlDocument rssDoc = new XmlDocument(); rssDoc.Load(rssStream); XmlNamespaceManager nsmgr = new XmlNamespaceManager(rssDoc.NameTable); nsmgr.AddNamespace(“dc”, “http://purl.org/dc/elements/1.1/”); XmlNodeList rssItems = rssDoc.SelectNodes(“rss/channel/item”); for (int i = 0; i < 5; i++) { XmlNode rssDetail = rssItems[i].SelectSingleNode(“dc:creator”, nsmgr); if (rssDetail != null) … Read more

How to change XML Attribute

Mike; Everytime I need to modify an XML document I work it this way: //Here is the variable with which you assign a new value to the attribute string newValue = string.Empty; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlFile); XmlNode node = xmlDoc.SelectSingleNode(“Root/Node/Element”); node.Attributes[0].Value = newValue; xmlDoc.Save(xmlFile); //xmlFile is the path of your file to be … Read more

What is the simplest way to get indented XML with line breaks from XmlDocument?

Based on the other answers, I looked into XmlTextWriter and came up with the following helper method: static public string Beautify(this XmlDocument doc) { StringBuilder sb = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = ” “, NewLineChars = “\r\n”, NewLineHandling = NewLineHandling.Replace }; using (XmlWriter writer = XmlWriter.Create(sb, settings)) … Read more