how to append a xml file in c#?
i am adding tracing for audit purposes of a simple process i have built as an .exe and set in the scheduler to run every 10 minutes. i want to have the application output the results into an xml file.
if the file exists then open and append data to it, if it does not exist i want to create a new xml file that will be persisted and used on next run.
here is my code now, what do i need to add, how do i open the xml file (on c:/file.xml) and use it to append nodes to?
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
doc.AppendChild(dec);// Create the root element
XmlElement root = doc.CreateElement("STATS");
doc.AppendChild(root);
XmlElement urlNode = doc.CreateElement("keepalive");
urlNode.SetAttribute("runTime", DateTime.Now.ToString());
try
{
WebProxy开发者_开发百科 wp = new WebProxy("http://proxy.ml.com:8083/");
WebClient w = new WebClient();
w.Proxy = wp;
if (w.DownloadString("http://wwww.example.com") != "")
urlNode.SetAttribute("result", "UP");
else
urlNode.SetAttribute("result", "DOWN");
}
catch
{
urlNode.SetAttribute("result", "DOWN");
}
finally
{
root.AppendChild(urlNode);
doc.Save("c:/keepAlive.xml");
}
}
You can't append an XML file - you'll have to load the file in memory , modify/add/etc, and then write it to disk.
EDIT :
Well, for loading a file you would use :
XmlDocument xmlDoc= new XmlDocument(); // create an xml document object.
if(System.IO.File.Exists("yourXMLFile.xml")
xmlDoc.Load("yourXMLFile.xml");// load from file
else{
// create the structure of your xml document
XmlElement root = xmlDoc.CreateElement("STATS");
xmlDoc.AppendChild(root);
}
and then start adding the keepalive stuff.
I would actually go a bit further and not mess around with xml. I'd create a class that contains everything I need and just serialize and deserialize it.
Like this:
[XmlRoot]
public class Stats{
public Stats(){}
public IList<StatsItem> Items{get;set;}
}
public class StatsItem{
public StatsItem(){}
public string UrlName{get;set;}
public DateTime Date{get;set;}
}
now just serialize this, and you have your xml document. When the time comes, deserialize it, add stuff to the Items list and serialize and save it to disk again.
There are lots of resources on google , so just search a bit for those.
using System;
using System.Xml.Linq;
using System.Xml.XPath;
...
public void Append(){
XDocument xmldoc = XDocument.Load(@"yourXMLFile.xml"));
XElement parentXElement = xmldoc.XPathSelectElement("yourRoot");
XElement newXElement = new XElement("test", "abc");
//append element
parentXElement.Add(newXElement);
xmldoc.Save(@"yourXMLFile.xml"));
}
精彩评论