简体   繁体   中英

creating new xml file by C#

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 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);
    }

如果您唯一要做的就是将字符串另存为文件(并且您不想执行XML特定的工作,例如检查格式正确或自动缩进),则只需使用File.WriteAllText()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM