I need to create an xml file here
bool result= false;
How to achieve this in ASP.NET with C# syntax. result
is value that I need to add in the XML file.
I need to create an XML file under a folder with contents like this
开发者_StackOverflow<?xml version="1.0" encoding="utf-8" ?>
<user>
<Authenticated>yes</Authenticated>
</user>
thank you
XElement xml = new XElement("user",
new XElement("Authenticated","Yes"))
);
xml.Save(savePath);
It works for .net 3 and above, but You can use XmlDocument for later versions
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);
You can use XmlWriter too as suggests @marc_s or at least you can store xml to the file like sting
using(StreamWriter sw = new StreamWriter(savePath))
{
sw.Write(string.Format("<?xml version=\"1.0\" encoding=\"utf-8\" ?>
<user><Authenticated>{0}</Authenticated></user>","Yes"));
}
How about this:
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();
Or if you prefer to build up your XML file in memory, you can also use the XmlDocument
class and its methods:
// 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");
Should work on any version of the .NET framework, if you have a using System.Xml;
clause at the top of your file.
Marc
If you want to generate the XML and then give the user a choice to save the XML in their workstation, check the post below. It explains that process in detail.
Generating XML in Memory Stream and download
精彩评论