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

Getting specified Node values from XML document

Just like you do for getting something from the CNode you also need to do for the ANode XmlNodeList xnList = xml.SelectNodes(“/Element[@*]”); foreach (XmlNode xn in xnList) { XmlNode anode = xn.SelectSingleNode(“ANode”); if (anode!= null) { string id = anode[“ID”].InnerText; string date = anode[“Date”].InnerText; XmlNodeList CNodes = xn.SelectNodes(“ANode/BNode/CNode”); foreach (XmlNode node in CNodes) { XmlNode … 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