tags:

views:

688

answers:

6

Hi everyone,

I have a string and its value is:

<ROOT>
    qwerty
    <SampleElement>adsf</SampleElement> 
    <SampleElement2>The text of the sample element2</SampleElement2> 
</ROOT>

How can I write this string to a file using C# 3.0?

Thanks in advance.

A: 

You'll have to use CDATA section. More specifically, create a XmlCDataSection using XmlDocument.CreateCDataSection and supply your string as a parameter.

Anton Gogolev
+6  A: 

Try this:

string s = "<xml><foo></foo></xml>";
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(s);
xdoc.Save("myfilename.xml");

Has the added benefit that the load will fail if your XML is invalid.

jvenema
+2  A: 
File.WriteAllText("myFile.xml",myString);
BFree
A: 

you could alway use XLINQ. check here for a quick primer....

Muad'Dib
A: 

I know you said C# but have you tried VB.NET for XML Literals. Amazing stuff.

Public Class Program
    Public Shared Sub Main()
        Dim myKeyBoardStyle = "dvorak"

        Dim myXML As XElement = <ROOT>
                                qwerty
                                <altKeyboard><%= myKeyBoardStyle.ToUpper() %></altKeyboard>
                                    <SampleElement>adsf</SampleElement>
                                    <SampleElement2>The text of the sample element2</SampleElement2>
                                </ROOT>

        Console.WriteLine(myXML.ToString())

        myXML.Save(".\fileFromXElement.xml")
    End Sub
End Class

Notice the neat element which injects the result of code in into the output:

<?xml version="1.0" encoding="utf-8"?>
<ROOT>
                                qwerty
                                <altKeyboard>DVORAK</altKeyboard><SampleElement>adsf</SampleElement><SampleElement2>The text of the sample element2</SampleElement2></ROOT>

snip [removed opinions]

Mike Bonnell
This is not a case of the right tool for the job. Your post is an example of the limitations of only knowing one tool and trying to force everything into it. If the OP is using C# for everything else, the introduction of VB.NET simply to save an XML string is ridiculous.
Ken White
No My post in an example of what an open mind can do by using projects of more than one language in the same solution. The VB language syntax is very easy to use for XML. I use both VB and C#.It is unclear how much "everything else" is done in C# by pragadheesh. Perhaps he explores alternatives.
Mike Bonnell
I still say introducing another language for the simple purpose of saving an XML string is ridiculous. Actually open your mind and think about what you're proposing: "Gee, I'll bring in a bulldozer, even though all I need is a trowel, to move this cup full of sand into the garden."
Ken White