<><><>...etc\"" />
开发者

creating new xml file by C#

开发者 https://www.devze.com 2023-01-26 08:04 出处:网络
how we can create new xml file by C# in the following situation: its winform. our xml code is in a string str = \"<><><><>...etc\"

how we can create new xml file by C# in the following situation:

  1. its winform.
  2. our xml code is in a string str = "<><><><>...etc"

now i want to create an xml file 开发者_JAVA技巧myxml.xml which contains everything in str,

please answer in the context and thanks... need simple source code


XmlDocument.LoadXml

using System;
using System.Xml;

public class Sample {

  public static void Main() {

    // Create the XmlDocument.
    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<item><name>wrench</name></item>"); //Your string here

    // Save the document to a file and auto-indent the output.
    XmlTextWriter writer = new XmlTextWriter("data.xml",null);
    writer.Formatting = Formatting.Indented;
    doc.Save(writer);
  }
}


Hi how about creating a method just for this:

private static void CreateXMLFile(string xml, string filePath)
    {
        // Create the XmlDocument.
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml); //Your string here

        // Save the document to a file and auto-indent the output.
        XmlTextWriter writer = new XmlTextWriter(filePath, null);
        writer.Formatting = Formatting.Indented;
        doc.Save(writer);
    }


If the only thing you want to do is to save the string as a file (and you don't want to do do XML-specific stuff like checking well-formedness or automatic indenting), you can simply use File.WriteAllText().

0

精彩评论

暂无评论...
验证码 换一张
取 消