2009-10-09 86 views
2

我需要在這裏創建如何生成一個XML文件

bool result= false; 

一個XML文件如何在ASP.NET中使用C#語法實現這一目標。 result是我需要在XML文件中添加的值。

我需要創建一個文件夾下的XML文件,像這樣

<?xml version="1.0" encoding="utf-8" ?> 
<user> 
    <Authenticated>yes</Authenticated> 
</user> 

內容謝謝

回答

2

如何:

XmlTextWriter xtw = new XmlTextWriter(@"yourfilename.xml", Encoding.UTF8); 

xtw.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\""); 
xtw.WriteStartElement("user"); 
xtw.WriteStartElement("Authenticated"); 
xtw.WriteValue(result); 
xtw.WriteEndElement(); // Authenticated 
xtw.WriteEndElement(); // user 

xtw.Flush(); 
xtw.Close(); 

或者如果你喜歡建立在內存中的XML文件,你也可以使用XmlDocument類及其方法:

// Create XmlDocument and add processing instruction 
XmlDocument xdoc = new XmlDocument(); 
xdoc.AppendChild(xdoc.CreateProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"")); 

// generate <user> element 
XmlElement userElement = xdoc.CreateElement("user"); 

// create <Authenticated> subelement and set it's InnerText to the result value   
XmlElement authElement = xdoc.CreateElement("Authenticated"); 
authElement.InnerText = result.ToString(); 

// add the <Authenticated> node as a child to the <user> node 
userElement.AppendChild(authElement); 

// add the <user> node to the XmlDocument 
xdoc.AppendChild(userElement); 

// save to file 
xdoc.Save(@"C:\yourtargetfile.xml"); 

應在.NET Framework的任何版本,如果你有你的文件的頂部using System.Xml;條款。

馬克

+0

謝謝marc_s。 它工作的很好 – happysmile 2009-10-09 10:44:10

3
XElement xml = new XElement("user", 
        new XElement("Authenticated","Yes")) 
       ); 
xml.Save(savePath); 

它適用於.NET 3以上,但 您可以使用XmlDocument的對更高版本

XmlDocument xmlDoc = new XmlDocument(); 

    // Write down the XML declaration 
    XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0","utf-8",null); 

    // Create the root element 
    XmlElement rootNode = xmlDoc.CreateElement("user"); 
    xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement); 
    xmlDoc.AppendChild(rootNode); 

    // Create the required nodes 
    XmlElement mainNode = xmlDoc.CreateElement("Authenticated"); 
    XmlText yesText= xmlDoc.CreateTextNode("Yes"); 
    mainNode.AppendChild(yesText); 

    rootNode.AppendChild(mainNode); 

    xmlDoc.Save(savePath); 

您也可以使用XmlWriter作爲建議@marc_s或至少你可以存儲XML的文件中像刺

using(StreamWriter sw = new StreamWriter(savePath)) 
{ 
sw.Write(string.Format("<?xml version=\"1.0\" encoding=\"utf-8\" ?> 
<user><Authenticated>{0}</Authenticated></user>","Yes")); 
} 
+0

我沒有找到name屬性一樣的XElement – happysmile 2009-10-09 09:50:03

+0

它的作品.NET 3.5及以上 – 2009-10-09 10:19:10

1

如果你想生成XML,然後給用戶一個選擇保存XML在他們的工作站,檢查下面的文章。它詳細解釋了這個過程。

Generating XML in Memory Stream and download

+0

提供示例代碼可以保證您的文章對未來用戶有用。 ;) – vdbuilder 2012-11-07 18:08:51