如何将XML字符串写入文件?

我有一个字符串,其值为:

 qwerty adsf The text of the sample element2  

如何使用C#3.0将此字符串写入文件?

提前致谢。

试试这个:

 string s = ""; XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(s); xdoc.Save("myfilename.xml"); 

如果您的XML无效,还有一个额外的好处就是加载会失败。

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

你必须使用CDATA部分 。 更具体地说,使用XmlDocument.CreateCDataSection创建一个XmlCDataSection并提供您的字符串作为参数。

我知道你说过C#,但是你试过VB.NET for XML Literals。 惊人的东西。

 Public Class Program Public Shared Sub Main() Dim myKeyBoardStyle = "dvorak" Dim myXML As XElement =  qwerty <%= myKeyBoardStyle.ToUpper() %> adsf The text of the sample element2  Console.WriteLine(myXML.ToString()) myXML.Save(".\fileFromXElement.xml") End Sub End Class 

注意整齐的元素将代码的结果注入到输出中:

   qwerty DVORAKadsfThe text of the sample element2 

剪掉[删除的意见]