How do I write an XML string to a file?

走远了吗. 提交于 2019-11-27 03:05:19

问题


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.


回答1:


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.




回答2:


File.WriteAllText("myFile.xml",myString);



回答3:


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




回答4:


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]



来源:https://stackoverflow.com/questions/590881/how-do-i-write-an-xml-string-to-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!