我正在尝试使用以下结构创建XML文件
但是,这就是我得到的(一行):
<?xml version="1.0" encoding="utf-8"?><!--This file is generated by the program.--><root><OFBM time="9:15" date="22.06.2016"><folder>file:///C:/Program Files (x86)/Cisco/Cisco AnyConnect Secure Mobility Client</folder><folder>file:///C:/Arduino223</folder></OFBM></root>
我的代码:
public void CreateXML()
{
XmlWriter writer = XmlWriter.Create(@"C:\Users\Alek\Dropbox\D\Debug\product.xml");
writer.WriteStartDocument();
writer.WriteComment("This file is generated by the program.");
writer.WriteStartElement("root");
writer.WriteStartElement("OFBM");
writer.WriteAttributeString("time", "9:15");
writer.WriteAttributeString("date", "22.06.2016");
writer.WriteElementString("folder", @"file:///C:/Program Files (x86)/Cisco/Cisco AnyConnect Secure Mobility Client");
writer.WriteElementString("folder", @"file:///C:/Arduino223");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();
}
我如何追加新数据?而不是每次都创建一个新的XML。
答案 0 :(得分:0)
添加一些设置以实现您尝试在XML文件中完成的缩进:
//I added this part (XmlWriterSettings):
XmlWriterSettings mySettings = new XmlWriterSettings();
mySettings.Indent = true;
mySettings.IndentChars = (" ");
mySettings.CloseOutput = true;
mySettings.OmitXmlDeclaration = true;
//Added the settings you intialize and set on your XmlWriter:
XmlWriter writer = XmlWriter.Create(@"C:\Users\Alek\Dropbox\D\Debug\product.xml", mySettings);
writer.WriteStartDocument();
writer.WriteComment("This file is generated by the program.");
writer.WriteStartElement("root");
writer.WriteStartElement("OFBM");
writer.WriteAttributeString("time", "9:15");
writer.WriteAttributeString("date", "22.06.2016");
writer.WriteElementString("folder", @"file:///C:/Program Files (x86)/Cisco/Cisco AnyConnect Secure Mobility Client");
writer.WriteElementString("folder", @"file:///C:/Arduino223");
writer.WriteEndElement();
//writer.WriteEndElement();
//writer.WriteEndDocument();
writer.Flush();
writer.Close();
要在不重新创建文件的情况下附加新数据,您可以执行以下操作:
XDocument doc = XDocument.Load(@"C:\Users\Alek\Dropbox\D\Debug\product.xml");
XElement school = doc.Element("root");
school.Add(new XElement("OFBM",
new XElement("folder", "file:///C:/Arduino223")));
doc.Save(@"C:\Users\Alek\Dropbox\D\Debug\product.xml");