2010-11-21 60 views
-1

創建新的XML文件如何,我們可以通過C#在下列情況下創建新的XML文件:通過C#

  1. 它的winform。
  2. 我們的XML代碼在字符串str = 「<> <> <> <> ...等」

現在我想創建一個包含在STR一切XML文件myxml.xml

請回答的背景和感謝... 需要簡單的源代碼

+1

我認爲他已經串XML標籤,並希望將它們保存到一個物理文件 - > myxml.xml – 2010-11-21 13:38:41

+0

@Aseem:到底是什麼我想 – salman 2010-11-21 13:40:02

回答

4

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

非常感謝它的確切答案 – salman 2010-11-21 13:47:31

1

如果您想要做的唯一事情就是將字符串保存爲文件(並且您不想執行特定於XML的內容,例如檢查格式良好或自動縮進),那麼可以簡單地使用File.WriteAllText()

3

喜怎麼樣在這個剛剛創建的方法:

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