C# 如何将 XML 字符串写入文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/590881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I write an XML string to a file?
提问by
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?
如何使用 C# 3.0 将此字符串写入文件?
Thanks in advance.
提前致谢。
回答by Anton Gogolev
You'll have to use CDATA section. More specifically, create a XmlCDataSectionusing XmlDocument.CreateCDataSectionand supply your string as a parameter.
您必须使用CDATA 部分。更具体地说,创建一个XmlCDataSectionusingXmlDocument.CreateCDataSection并将您的字符串作为参数提供。
回答by jvenema
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.
如果您的 XML 无效,加载将会失败。
回答by BFree
File.WriteAllText("myFile.xml",myString);
回答by Mike Bonnell
I know you said C# but have you tried VB.NET for XML Literals. Amazing stuff.
我知道您说的是 C#,但是您是否尝试过 VB.NET for XML Literals。惊人的东西。
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]
剪[删除意见]

