我正在为一个简单的过程添加跟踪,这个过程是作为一个.exe生成的,并在调度程序中设置为每10分钟运行一次。我想让应用程序将结果输出到一个xml文件中。如何在c#中添加一个xml文件?
如果文件存在,然后打开并追加数据,如果它不存在,我想创建一个新的xml文件,它将被保留并在下次运行时使用。
这里是我的代码现在,我需要添加什么,我如何打开xml文件(在c:/file.xml)并使用它来追加节点?
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");
}
}
您已经拥有了大部分解决方案 - 您正在创建节点将它们添加并保存。如果如何从文件读取是真正的问题,我建议您查看MSDN上的XmlDocument的构造函数重载。 – annakata 2010-11-22 14:53:15