用于不同xml文件的XML Serializer和Deserializer类

时间:2015-10-28 02:34:14

标签: c# xml serialization xml-serialization xml-deserialization

我有两种不同格式的xml文件,需要使用C#进行序列化和反序列化。

XML文件 输入1:

<?xml version="1.0"?>
<tms_msg>
    <transaction>
        <message_string>Left Over</message_string>
    </transaction>
</tms_msg>

类型2:

<?xml version="1.0"?>
<tms_msg>
    <transaction>
        <message_string>
            <utc_date_time>0001-01-01T00:00:00</utc_date_time>
            <utctime>000000</utctime>
            <latitude/>
            <latitude_hemi/>
            <longitude/>
            <longitude_hemi/>
            <speed/>
            <heading>000</heading>
        </message_string>
    </transaction>
</tms_msg>

如何序列化和反序列化两个不同的xml文件? 我需要一个可以对这些xml文件进行序列化和反序列化的类。

//更新代码

public class MessageReceiver 
{
    private MessageQueue _queue;
    private readonly string _queueName;

    public MessageReceiver()
    {
        this._queueName = @".\Private$\to_dispatch";
    }

    public void StartRead()
    {
        _queue = new MessageQueue(_queueName);
        _queue.PeekCompleted += QueuePeekCompleted;

    }

    private void QueuePeekCompleted(object sender, PeekCompletedEventArgs e)
    {
        var message = _queue.EndPeek(e.AsyncResult);         
        message.Formatter = new XmlMessageFormatter(new Type[] { typeof(tms_msg) });
        Console.WriteLine(string.Format("The message was: {0}", message.Id));
        var m = message.Body;            
        Console.WriteLine(string.Format("The QueuePeek is completed message was: {0}", message.Id));      
    }

    public override string ToString()
    {
        return _queueName;
    }
}

我在MSMQ消息队列场景中使用。

谢谢, Binod

2 个答案:

答案 0 :(得分:1)

您可以在message_string中将transaction视为动态。见下文:

[XmlRoot("tms_msg")]
public class TmsMsg
{
    [XmlElement("transaction")]
    public Transaction Transaction { get; set; }
}

public class Transaction
{
    [XmlElement("message_string")]
    public dynamic MessageString { get; set; }
}

反序列化:

public void Deserialize()
{
    TmsMsg msg = null;
    var msgDict = new Dictionary<string, string>();

    using (var stream = new FileStream("Type2.xml", FileMode.Open))
    {
        XmlSerializer ser = new XmlSerializer(typeof(TmsMsg));
        msg = ser.Deserialize(stream) as TmsMsg;
    }

    // type 1 : message_string element has a xml text node
    // type 2 : message_string element has a xml elements
    foreach (var node in msg.Transaction.MessageString)
    {
        if (node.NodeType == XmlNodeType.Text)
        {
            msgDict.Add("message_string", node.Value);
        }
        else if (node.NodeType == XmlNodeType.Element)
        {
            msgDict.Add(node.Name, node.InnerText);
        }
    }
}

答案 1 :(得分:0)

我找到了答案,它正在发挥作用。 在上面的代码中更改以下内容。

[XmlElement("message_string")]
public dynamic message_string{ get; set; }

[XmlElement(typeof(string)), XmlElement(typeof(message_string))]
public dynamic message_string{ get; set; }

并将类名Message_String更改为message_string。