[英]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? 可以/应该使用XmlSerialiser来反序列化以下由第三方定义的,与xml类似的消息协议吗?
The protocol specifies a number of messages, some contain attributes others don't eg Protocol A 该协议指定了许多消息,有些包含一些其他属性,例如协议A
<GetEvent></GetEvent>
<GetEvent></GetEvent>
传输 <AckEvent>1234,888</AckEvent>
<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 我想使用XDocument对类进行反序列化(理想情况下,类将从xsd文件生成),例如
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. 但是没有属性的类将使用“最小化”的结束标记进行序列化:
<GetEvent />
,协议不允许这样做。
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: 同样,同一第三方设备具有另一个接口,该接口略有不同,因为属性将包含在标签中,例如协议B:
A SomeOtherEvent message with params would be transfered as the string <SomeOtherEvent><ID>1234</ID><TYPE>999</TYPE></SomeOtherEvent>
带有参数的SomeOtherEvent消息将作为字符串
<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. 但是仍然存在最小化没有参数的消息的结束标记的问题。
尝试使用XmlElement属性 。
The .Net XML classes can only work with well-formed XML. .Net XML类只能与格式正确的XML一起使用。 If this "XML-like" scheme is not well-formed, you will have to roll your own.
如果这种“类似XML的”方案格式不正确,则必须自己动手。
This wikipedia article has some basic rules about well-formedness. 这篇Wikipedia文章具有一些有关格式正确的基本规则。 For a complete definition, see the specification .
有关完整定义,请参见规范 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.