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

问题描述 投票:1回答:1

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

让我们假设我有以下类,我希望使用XmlSerializerfoo属性添加到Name标签中进行serizlize。

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答案,但无法找到有关它的任何信息。欢迎所有建议。

c# xml xml-serialization xmlserializer
1个回答
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; }
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.