Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to write string to XML file?

Status
Not open for further replies.

isarta

Programmer
May 15, 2007
8
EE
Hello Everybody,

This last days your site helped me a lot and I feel a litle bit shamed, that asking you all the time, but I'm the beginning programmer and for me your help is really very important.

So, I have another problem. I used web reference from weather site and get information like that: (for instance Tallinn, Estonia the place)

<?xml version="1.0" encoding="utf-16"?>
<CurrentWeather>
<Location>Tallinn, Estonia (EETN) 59-24N 024-49E 34M</Location>
<Time>May 22, 2007 - 03:50 AM EDT / 2007.05.22 0750 UTC</Time>
<Wind> from the SW (230 degrees) at 3 MPH (3 KT):0</Wind>
<Visibility> greater than 7 mile(s):0</Visibility>
<SkyConditions> overcast</SkyConditions>
<Temperature> 59 F (15 C)</Temperature>
<DewPoint> 50 F (10 C)</DewPoint>
<RelativeHumidity> 72%</RelativeHumidity>
<Pressure> 29.94 in. Hg (1014 hPa)</Pressure>
<Status>Success</Status>
</CurrentWeather>

And it goes like string. How can I save this information to xml file like xml.

Thank you,
Artashes.
 
More information:

The problem is, that I can convert string to xml, because my string is already looks like xml, so it will be like xml in xml. I was trying just to save it "as it is" to file with format .xml, but there some problems with encoding...
 
it may be that proper xml wants the inner text wrapped with a Cdata[] element especially for these symbols , : ( ).

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Create a StreamWriter or FileStream (System.IO) and write the string to a file. If you write the string as raw data and then reload it in an XmlDocument (System.Xml) then it should show up as XML.
 
Your XML says it is UTF-16 the default for saving to a stream is UTF-8 (I believe). You may want to change the first line, before saving, to:

<?xml version="1.0" encoding="utf-8"?>

or better still leave out the encoding as it isn't required for UTF-8 or UTF-16 anyway.

<?xml version="1.0"?>

Or you can change the code that saves the file to save using UTF-16 like this:

Code:
using System.IO;

// ...

        private void SaveFile(string xmlString)
        {
            using (StreamWriter sw = new StreamWriter("C:\\file.xml", false, Encoding.Unicode))
            {
                sw.Write(xmlString);
            }
        }
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top