反序列化取决于字段值

时间:2019-10-14 10:49:18

标签: c# xml-serialization

我需要反序列化使用字段“ type”指示期望内容的XML。 类型0表示我可以期望使用简单的文本,而类型1则表示内容具有更复杂的结构。

我知道我可以编写一些自定义反序列化机制,但是想知道是否有任何内置方法可以解决此问题。

由于XMLSerializer需要一个字符串,因此如果它是XML,它只会丢弃内容。这使我无法执行第二步的内容反序列化。

<Msg>
    <MsgType>0</MsgType>
    <Data>Some text</Data>
</Msg>

<Msg>
    <MsgType>1</MsgType>
    <Data>
        <Document>
            <Type>PDF</Type>
            .....
        </Document>
    </Data>
</Msg>

1 个答案:

答案 0 :(得分:0)

开箱即用不支持;但是,您也许可以使用:

public XmlNode Data {get;set;}

并运行“如何处理Data?”第二步,您可以查看MsgType

完整示例:

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

static class P
{
    static void Main()
    {
        const string xml = @"<Foo>
<Msg>
    <MsgType>0</MsgType>
    <Data>Some text</Data>
</Msg>

<Msg>
    <MsgType>1</MsgType>
    <Data>
        <Document>
            <Type>PDF</Type>
            .....
        </Document>
    </Data>
</Msg>
</Foo>";
        var fooSerializer = new XmlSerializer(typeof(Foo));
        var docSerializer = new XmlSerializer(typeof(Document));
        var obj = (Foo)fooSerializer.Deserialize(new StringReader(xml));

        foreach (var msg in obj.Messages)
        {
            switch (msg.MessageType)
            {
                case 0:
                    var text = msg.Data.InnerText;
                    Console.WriteLine($"text: {text}");
                    break;
                case 1:
                    var doc = (Document)docSerializer.Deserialize(new XmlNodeReader(msg.Data));
                    Console.WriteLine($"document of type: {doc.Type}");
                    break;
            }
            Console.WriteLine();
        }
    }
}
public class Foo
{
    [XmlElement("Msg")]
    public List<Message> Messages { get; } = new List<Message>();
}
public class Message
{
    [XmlElement("MsgType")]
    public int MessageType { get; set; }

    public XmlNode Data { get; set; }
}

public class Document
{
    public string Type { get; set; }
}
相关问题