【问题标题】:Setting a XML Element Name and XML Attribute to a Class Property将 XML 元素名称和 XML 属性设置为类属性
【发布时间】:2020-05-27 08:09:46
【问题描述】:

我有这个要转换为 XML 元素的类

public class Person
{
  [XmlElement(ElementName = "PersonName")]
  public string Name { get; set; }
}

这将显示一个 XML

<Person>
  <PersonName>Smith</PersonName>
</Person>

我想给元素 PersonName 添加一个属性

<Person>
  <PersonName required="true">Smith</PersonName>
</Person>

我该怎么做?

【问题讨论】:

标签: c# asp.net xml asp.net-mvc


【解决方案1】:

我认为你需要一个特殊的类来保存你的 Name 属性,而不是依赖于string。下面是一个示例,使用XmlTextXmlAttribute 属性来控制内置XmlSerializer 的工作方式:

using System.Xml.Serialization;
using System.IO;

namespace SomeNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            Person me = new Person("me");

            string path = "C:\\temp\\person.xml";
            XmlSerializer serializer = new XmlSerializer(typeof(Person));
            using (StreamWriter sw = new StreamWriter(path))
            {
                serializer.Serialize(sw, me);
            }
        }
    }

    public class Person
    {
        public Person() { } // needed for serialization
        public Person(string name)
        {
            Name = new PersonName(name);
        }

        [XmlElement(ElementName = "PersonName")]
        public PersonName Name { get; set; }
    }

    public class PersonName
    {
        public PersonName() { } // needed for serialization
        public PersonName(string name)
        {
            Name = name;
        }

        [XmlText]
        public string Name { get; set; }

        [XmlAttribute] // serializes as an Attribute
        public bool Required { get; set; } = true;
    }
}

输出(在 C:\temp\person.xml;如果需要,您可以更改 Main 以序列化为字符串并打印到控制台):

<?xml version="1.0" encoding="utf-8"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <PersonName Required="true">me</PersonName>
</Person>

如果你真的想让你的Required属性被序列化为小写的“required”,你可以使用XmlAttribute的不同属性,比如:XmlAttribute(AttributeName = "required")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    相关资源
    最近更新 更多