使用C#对象序列化的XML标记的自定义属性

时间:2018-02-28 08:40:50

标签: c# xml xml-serialization xmlserializer

我能用.NET完成这样的事吗?

假设我有以下类,我希望使用XmlSerializerfoo属性添加到Name标记来识别其对象。

public class Person {
    [SomeXMLTagAttribute(Name="foo", Value="bar")]
    public string Name { get; set;}
}

当序列化发生时,我希望结果为:

...
<Person>
  <Name foo="bar">John Doe</Name>
</Persion>

foobar是编译时常量。

不一定是C#属性(SomeXMLTagAttribute),但这是一个最小的例子。在实际案例中,我有很多嵌套类,我想要一种简单的方法来管理foobar

我已阅读文档和SO答案,但无法找到有关它的任何信息。欢迎提出所有建议。

1 个答案:

答案 0 :(得分:0)

使用xml Linq:

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

namespace ConsoleApplication25
{
    class Program
    {
       static void Main(string[] args)
        {

           XElement xml = new XElement("People", Person.people.Select(x => new XElement("Name", new object[] { new XAttribute("foo", x.attribute), x.value})));

        }
    }
    public class Person
    {
        public static List<Person> people = new List<Person>();


        public string Name { get; set; }
        public string attribute { get; set; }
        public string value { get; set; }
    }

}
相关问题