一尘不染

使用XmlWriter附加现有XML文件

c#

我使用以下代码创建XML文件:

XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = true;
xmlWriterSettings.NewLineOnAttributes = true;
using (XmlWriter xmlWriter = XmlWriter.Create("Test.xml", xmlWriterSettings))
{
   xmlWriter.WriteStartDocument();
   xmlWriter.WriteStartElement("School");
   xmlWriter.WriteEndElement();
   xmlWriter.WriteEndDocument();
   xmlWriter.Close();
 }

我需要动态创建以下结构来插入节点:

<?xml version="1.0" encoding="utf-8"?>
<School />
   <Student>
      <FirstName>David</FirstName>
      <LastName>Smith</LastName>
   </Student>
   ...
   <Teacher>
      <FirstName>David</FirstName>
      <LastName>Smith</LastName>
   </Teacher>
   ...
</School>

我该怎么做?应该从键盘上读取“ FirstName”和“ LastName”的值,并且可以随时输入这些值,当然在现有的情况下。


阅读 279

收藏
2020-05-19

共1个答案

一尘不染

终于我成功了:)

if (!File.Exists("Test.xml"))
{
   XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
   xmlWriterSettings.Indent = true;
   xmlWriterSettings.NewLineOnAttributes = true;
   using (XmlWriter xmlWriter = XmlWriter.Create("Test.xml", xmlWriterSettings))
   {
      xmlWriter.WriteStartDocument();
      xmlWriter.WriteStartElement("School");

      xmlWriter.WriteStartElement("Student");
      xmlWriter.WriteElementString("FirstName", firstName);
      xmlWriter.WriteElementString("LastName", lastName);
      xmlWriter.WriteEndElement();

      xmlWriter.WriteEndElement();
      xmlWriter.WriteEndDocument();
      xmlWriter.Flush();
      xmlWriter.Close();
   }
}
else
{
   XDocument xDocument = XDocument.Load("Test.xml");
   XElement root= xDocument.Element("School");
   IEnumerable<XElement> rows = root.Descendants("Student");
   XElement firstRow= rows.First();
   firstRow.AddBeforeSelf(
      new XElement("Student",
      new XElement("FirstName", firstName),
      new XElement("LastName", lastName)));
   xDocument.Save("Test.xml");
}
2020-05-19