【问题标题】:IXmlSerializable. XmlWriter. How to change root element?IXmlSerializable。 XmlWriter。如何更改根元素?
【发布时间】:2020-09-26 21:57:35
【问题描述】:

我需要以 2 种不同的方式将我的 Invoice 模型序列化为 Xml。

第一个序列化应该有“FirsName”作为根元素。

第二个“SecondName”。

有不同的实现方式,但我不知道如何实现它们。

要么避免根元素并手动添加它, 或者以某种方式动态预设它。

这是我的模型:

public class InvoiceInfo : IXmlSerializable
{
     public int InvoiceId { get; set; }
}

根据条件我想像这样序列化它:

<firstRoot>
    <invoiceId value="123" />
</firstRoot>

<secondRoot>
    <invoiceId value="123" />
</secondRoot>

也许可以通过调整 XmlWriter.Settings 解决?

我找到了这种方法,但它看起来很难看。因为它有点后期处理......

var duplicate =  XDocument.Parse(xmlDocument.InnerXml);
duplicate.Root.Name = "newRootName";
var res = duplicate.ToString();

【问题讨论】:

标签: c# xml ixmlserializable


【解决方案1】:

你可以使用XmlRootAttribute Class和继承:

    public abstract class InvoiceInfo 
    {
        public int InvoiceId { get; set; }
    }

    [XmlRoot("firstRoot")]
    public class FirstInvoiceInfo : InvoiceInfo
    {
    }

    [XmlRoot("secondRoot")]
    public class SecondInvoiceInfo : InvoiceInfo
    {
    }

【讨论】:

  • 感谢您的回答。我考虑过那个解决方案,但我会从控制器类中获得这个模型,并且方法应该总是接受一个实现。
【解决方案2】:

可以动态添加XmlRootAttribute

bool condition = true;

var xmlRoot = new XmlRootAttribute(condition ? "firstRoot" : "secondRoot");

var ser = new XmlSerializer(typeof(InvoiceInfo), xmlRoot);

var invoice = new InvoiceInfo { InvoiceId = 123 };

ser.Serialize(Console.Out, invoice);

你的模型

public class InvoiceInfo : IXmlSerializable
{
    public int InvoiceId { get; set; }

    public XmlSchema GetSchema()
    {
        throw new NotImplementedException();
    }

    public void ReadXml(XmlReader reader)
    {
        throw new NotImplementedException();
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteStartElement("invoiceId");
        writer.WriteAttributeString("value", InvoiceId.ToString());
        writer.WriteEndElement();
    }
}

请参阅Dynamically Generated Assemblies - 您必须缓存程序集。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多