将元素添加到数组

Add element to an array

我有一个 class Person 和一个对象 List<Person>.
此列表是 XML 序列化的。结果类似于:

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd... (etc)
  <Person>
    <Id>0</Id>
    <Name>Person 0</Name>
    <Birthday>2000-01-01T00:00:00</Birthday>
  </Person>
  <Person>
     ...
  </Person>
  <Person>
     ...
  </Person>
</ArrayOfPerson>

我想向此列表中添加一个新的 Person 对象。

使用 XmlSerializer<List<Person>> 我可以将完整的 XML 反序列化为 List<Person> 对象,添加我的 Person 并将其序列化回 XML。

在我看来这是在浪费处理能力!

有没有一种方法可以添加我的 Person 而不必将所有其他人的 XML 文本翻译成 Persons 对象并将它们翻译回文本?

我可以使用 XElement 解析我的 XML 以找到我的 ArrayOfPerson 并添加一个包含我的 Person 数据的新 XElement。 SO 上有几个答案表明了这一点。

但是,要创建这个 XElement,我必须枚举 Person 的属性。获取值并将子元素添加到我的 XElement.

是否有一些 class 方法可以从对象创建 XElement,例如:

Person myPerson = ...
XElement xmlPerson = XElement.ToXml<Person>(myPerson);

还是必须自己写?

或者有更好的方法?

使用 XML LINQ:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication1
{
    public class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        private static void Main()
        {
            StreamReader reader = new StreamReader(FILENAME);
            reader.ReadLine(); //skip the unicode encoding in the ident

            XDocument doc = XDocument.Load(reader);
            XElement arrayOfPerson = doc.Descendants("ArrayOfPerson").FirstOrDefault();

            arrayOfPerson.Add(new XElement("Person"), new object[] {
                new XElement("Id", 0),
                new XElement("Name", "Person 0"),
                new XElement("Birthday", DateTime.Now.ToLongDateString()),
            });
        }
    }
}