If you want to preserve white spaces and indentation when saving, use
this technique:
1. After creating the xml document, set its PreserveWhitespace
property to true:
System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
xmlDocument.PreserveWhitespace = true; //this preserves white spaces
so that they won't be eliminated when loading the document
2. Instead of simply calling xmlDocument.Save(...), replace
xmlDocument.Save(...) with the following lines of code:
XmlTextWriter tw = new XmlTextWriter(<filename>, Encoding.ASCII);
try {
tw.Formatting = Formatting.Indented; //this preserves indentation
xmlDocument.Save(tw);
}
finally {
tw.Close();
}
I'm frequently using this method as I'm manipulating xml document that
should remain on disk and should be easily readable by a human user
that uses a simple text editor/viewer.
Hope this helps too
Moty Michaely a scris:
On May 25, 8:50 am, Hooyoo <zhao_huy...@126.comwrote:
I have a XML file as following:
<configuration>
<MachineList>
<Machine Name="mycomputer"/>
</MachineList>
</configuration>
How can I program to change "mycomputer" to "somecomputer"? Any
comments will be appreciated.
Hi,
Use XmlDocument to load the xml and then navigate through it to find
the element that contains the value you want to change.
System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
xmlDocument.Load(<filename or stream>);
Now, choose the most suitable method for you to find the elements or
attributes you want to change:
// For example:
XmlNodeList elemList = xmlDocument .GetElementsByTagName("Machine");
for (int i=0; i < elemList.Count; i++)
{
elemList[i].InnerXml = "somecomputer";
}
Then, call the Save method to save the changes.
xmlDocument.Save(...);
Hope this helps,
Moty