在 c# 中继续写入相同的 XML 文件而不删除

continue writing on same XML file without deleting in c#

到目前为止我已经完成了这段代码,但唯一的问题是每次我使用 addUser 方法时 XML 文件都会被删除,我希望代码继续在它下面编写

我用c#写的代码:

 public static void AddUser(PersonData pd)
        {
            XmlTextWriter xWriter = new XmlTextWriter("D:\PersonData.Xml", Encoding.UTF8);
            xWriter.Formatting = Formatting.Indented;
            xWriter.WriteStartElement("User");
            xWriter.WriteAttributeString("idNumber", pd.IdNumber1);

            xWriter.WriteStartElement("Firstname");
            xWriter.WriteString(pd.FirstName1);
            xWriter.WriteEndElement();//<FirstName>

            xWriter.WriteStartElement("LastName");
            xWriter.WriteString(pd.LastName1);
            xWriter.WriteEndElement();//<LastName>

            xWriter.WriteStartElement("DateOfBirth");
            xWriter.WriteString(pd.DateOfBirth1.ToString());
            xWriter.WriteEndElement();//<DateOfBirth>

            xWriter.WriteStartElement("Address");
            xWriter.WriteString(pd.Address1);
            xWriter.WriteEndElement();//<Address>

            xWriter.WriteEndElement();//<user>
            xWriter.Close();
        }

XML输出:

<User idNumber="316447077">
  <Firstname>majd</Firstname>
  <LastName>sadi</LastName>
  <DateOfBirth>29/03/1998 14:54:50</DateOfBirth>
  <Address>hohos</Address>
</User>

我想做的XML输出:

 <User idNumber="316447077">
      <Firstname>majd</Firstname>
      <LastName>sadi</LastName>
      <DateOfBirth>29/03/1998 14:54:50</DateOfBirth>
      <Address>hohos</Address>
    </User>
    <User idNumber="316447077">
      <Firstname>majd</Firstname>
      <LastName>sadi</LastName>
      <DateOfBirth>29/03/1998 14:54:50</DateOfBirth>
      <Address>hohos</Address>
    </User>

在写完结束元素后尝试像 xWriter.Flush() 一样刷新?

假设您有一个 XML 的根节点(没有它无效 XML),您可以使用 XElement:

XElement xe;

if (File.Exists("D:\PersonData.Xml"))
  xe = XElement.Load("D:\PersonData.Xml");
else
  xe = new XElement("Users");

XElement newUser = new XElement("User");
newUser.Add(new XAttribute("idNumber", pd.IdNumber1));
newUser.Add(new XElement("Firstname", pd.FirstName1));
newUser.Add(new XElement("LastName", pd.LastName1));
newUser.Add(new XElement("DateOfBirth", pd.DateOfBirth1.ToString()));
newUser.Add(new XElement("Address", pd.Address1));

xe.Add(newUser);
xe.Save("D:\PersonData.Xml");