How to write a string into a xml file on c#?

user1051434 picture user1051434 · Oct 1, 2012 · Viewed 9.5k times · Source

I've created a xml file using c#.

XmlTextWriter writer = new XmlTextWriter("Product.xml", System.Text.Encoding.UTF8);
writer.WriteStartDocument(true);
writer.Formatting = Formatting.Indented;
writer.Indentation = 2;

Then, I create my string:

string stringXML = string.Empty;
stringXML = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><configurations xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"configurations.xsd\"><ProductsList><Product><ID>1</ID><Description>EPR</Description></Product></ProductsList></configurations>";

Then I want to write my stringXML into Product.xml file.

I've tried :

System.IO.File.WriteAllText("Product.xml", stringXML);

but it doesn't worked...

How can I do this?

Answer

Usman picture Usman · Oct 1, 2012

Try it as

string s = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><configurations xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"configurations.xsd\"><ProductsList><Product><ID>1</ID><Description>EPR</Description></Product></ProductsList></configurations>";
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(s);
xdoc.Save("Product.xml");

Update

string name = saveFileDialog1.FileName;
string s = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><configurations xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"configurations.xsd\"><ProductsList><Product><ID>1</ID><Description>EPR</Description></Product></ProductsList></configurations>";
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(s);
xdoc.Save(name);

Since saveFileDialog1 is your SaveFileDialog