将元素添加到数组

时间:2018-08-23 13:31:08

标签: c# xml xmlserializer

我有一个类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并添加一个包含XElement数据的新Person。在SO上有几个答案可以说明这一点。

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

是否存在一些可以从对象创建XElement的Method类,例如:

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

还是我必须自己写这个?

或者也许有更好的方法?

1 个答案:

答案 0 :(得分:0)

使用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()),
            });
        }
    }
}
相关问题