How to generate XML file
I need to create xml file here
bool result= false;
How to achieve this in ASP.NET with C # syntax. result
is the value I need to add to the XML file.
I need to create an XML file under a folder with content like this
<?xml version="1.0" encoding="utf-8" ?>
<user>
<Authenticated>yes</Authenticated>
</user>
Thank you
source to share
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 create your XML file in memory, you can also use the class XmlDocument
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 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 suggestion using System.Xml;
at the top of the file.
Mark
source to share
XElement xml = new XElement("user",
new XElement("Authenticated","Yes"))
);
xml.Save(savePath);
It works for .net 3 and up, 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 also use XmlWriter as @marc_s suggests, or at least you can store xml in a 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"));
}
source to share