【问题标题】:How to change name of the root element with IXmlSerializable?如何使用 IXmlSerializable 更改根元素的名称?
【发布时间】:2018-08-09 21:09:11
【问题描述】:

我有下面代码的 sn-p,它使用IXmlSerializable 将类Person 的简单实例序列化为<Person attribute="value" />

using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

public class Person : IXmlSerializable
{
    public XmlSchema GetSchema()
    {
        return null;
    }
    public void ReadXml(XmlReader xmlReader)
    {
        throw new System.NotImplementedException();
    }
    public void WriteXml(XmlWriter xmlWriter)
    {
        xmlWriter.WriteAttributeString("attribute", "value");
    }
}

class Program
{    
    public static void Main()
    {
        var xmlWriterSettings = new XmlWriterSettings
        {
            Indent = true,
            OmitXmlDeclaration = true
        };

        using (var xmlTextWriter = XmlWriter.Create(Console.Out, xmlWriterSettings))
        {
            var xmlSerializer = new XmlSerializer(typeof(Person));
            var person = new Person();
            xmlSerializer.Serialize(xmlTextWriter, person);
        }
    }
}

我正在寻找将Person的元素名称修改为person的方法,我该怎么做?

【问题讨论】:

标签: c# .net xml serialization xml-serialization


【解决方案1】:

您可以使用XmlRootAttribute 指定根元素的元素名称:

[XmlRoot(ElementName = "person")]
public class Person : IXmlSerializable
{
    ...
}

【讨论】:

  • 你知道如何添加前缀命名空间,即使使用 IXmlSerializable 也可以添加这种属性?
  • @EhouarnPerret:您也可以在属性中为元素指定命名空间。我不确定如何给它一个特定的前缀——这可能值得在另一个问题中提出(当然是在研究之后)。
  • 关于前缀似乎到目前为止我看到的每个问题都没有找到任何可行的解决方案
  • @EhouarnPerret:好的,如果有重复的问题没有答案,这表明它可能是不可能的。 (老实说,我不太确定您在寻找什么,而且我也不是 XML 序列化专家。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多