简体   繁体   中英

Serialize classes to 'almost' xml strings in c#

Can/should XmlSerialiser be used to de/serialize the following, 3rd party defined, message protocol that is 'similiar' to xml?

The protocol specifies a number of messages, some contain attributes others don't eg Protocol A

  • A GetEvent message is to be transfered as the string <GetEvent></GetEvent>
  • A AckEvent message is to be transfered with 2 params as the string <AckEvent>1234,888</AckEvent>

I would like to use XDocument to do the de/serialization to/from classes (ideally the classes would be generated from an xsd file) eg

class GetEvent{}
class AckEvent{int ID; int Type;}

But classes with no attributes get serialized with a 'minimised' closing tag : <GetEvent /> which is not allowed by the protocol.

Also, the same 3rd party device has another interface that is slightly different in that the attributes are to be enclosed in tags eg Protocol B:

A SomeOtherEvent message with params would be transfered as the string <SomeOtherEvent><ID>1234</ID><TYPE>999</TYPE></SomeOtherEvent>

I can serialize these using:

public static XDocument Serialize<T>(T source)
{
    XDocument target = new XDocument();

    XmlSerializer s = new XmlSerializer(typeof(T));
    System.Xml.XmlWriter writer = target.CreateWriter();

    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    ns.Add("", "");

    s.Serialize(writer, source, ns);

    writer.Close();
    return target;
}

But still have the problem of minimised closing tag for messages without params.

  • How can I specify that Protocol A attributes be serialized as comma separated values instead of being enclosed in tags?
  • How can I specify that a 'non minimised' closing tag is used for messages without parameters for either Protocol?
  • Is using the XmlSerialisation framework appropriate for the above or is it not XML enough? If not what would be the simplest cleanest approach?

尝试使用XmlElement属性

The .Net XML classes can only work with well-formed XML. If this "XML-like" scheme is not well-formed, you will have to roll your own.

This wikipedia article has some basic rules about well-formedness. For a complete definition, see the specification .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM