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 AID nodes
foreach (XmlNode aNode in aNodes)
{
// grab the "id" attribute
XmlAttribute idAttribute = aNode.Attributes["id"];
// check if that attribute even exists...
if (idAttribute != null)
{
// if yes - read its current value
string currentValue = idAttribute.Value;
// here, you can now decide what to do - for demo purposes,
// I just set the ID value to a fixed value if it was empty before
if (string.IsNullOrEmpty(currentValue))
{
idAttribute.Value = "515";
}
}
}
// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");
Answer from marc_s on Stack OverflowYou can just open a new file, write the string and the Content of the old file.
ifstream oldXML("path/to/old/xml");
ofstream newXML("path/to/new/xml");
newXML<<"<!DOCTYPE people SYSTEM \"new_xmll.dtd\">"<<endl; //Write first line
newXML<<oldFile; //Copy Content of old file
You can also use a XML library if you want to Change any XML values. I like tinyxml a lot
Then probably TinyXML or MSXML would be interesting for you.
You could use the XDocument class:
var doc = XDocument.Load("test.xml");
var address = doc.Root.Element("address");
if (address != null)
{
address.Value = "new value";
}
doc.Save("test.xml");
Let's say you have the following XML file:
<root>
<address>myaddr</address>
</root>
And you want to do the replacement. There are many options. Some are explicitly modifying XML, others are translating your XML to classes, modifying and translating back to XML (serialization). Here is one of the ways do do it:
XDocument doc = XDocument.Load("myfile.xml");
doc.Root.Element("address").Value = "new address"
doc.Save("myfile.xml")
For more information read the following:
LINQ to XML is the technique I used here - http://msdn.microsoft.com/en-us/library/bb387098.aspx
XML serialization is another technique - http://msdn.microsoft.com/en-us/library/182eeyhh.aspx
Well, If you want to update a node in XML, the XmlDocument is fine - you needn't use XmlTextWriter.
XmlDocument doc = new XmlDocument();
doc.Load("D:\\build.xml");
XmlNode root = doc.DocumentElement;
XmlNode myNode = root.SelectSingleNode("descendant::books");
myNode.Value = "blabla";
doc.Save("D:\\build.xml");
Using LINQ to xml if you are using framework 3.5
using System.Xml.Linq;
XDocument xmlFile = XDocument.Load("books.xml");
var query = from c in xmlFile.Elements("catalog").Elements("book")
select c;
foreach (XElement book in query)
{
book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");