在类型之间共享一组 XmlElementAttribute 修饰的字段
我的几个 XML 可序列化类型共享相同的属性集,我想将它们重构为单个类型以删除重复项,如下所示。
public class RequestHeader
{
[XmlElement]
public string UserId { get; set; }
[XmlElement]
public string RequestId { get; set; }
}
[XmlRoot]
public class RequestType
{
public RequestHeader Header { get; set; }
// ... other fields ...
}
[XmlRoot]
public class AnotherRequestType
{
public RequestHeader Header { get; set; }
// ... other fields ...
}
序列化这两种类型中的任何一种时,序列化程序都会将 Header
属性的内容包含在
元素中。是否有一个属性可以装饰 Header
属性,以便不呈现父
元素?我在序列化集合属性时成功完成了此操作,但我不确定是否可以使用单个元素来完成此操作。<RequestHeader>
<Header> <!-- omit this -->
<UserId>user</UserId>
<RequestId>123</RequestId>
</Header> <!-- omit this -->
</RequestHeader>
或者,我可以诉诸继承或具有一个元素的集合,但这些选项中的任何一个都不能提供干净的编程模型。
Several of my XML-serializable types share the same set of properties, and I would like to refactor them into a single type to remove the duplication as follows.
public class RequestHeader
{
[XmlElement]
public string UserId { get; set; }
[XmlElement]
public string RequestId { get; set; }
}
[XmlRoot]
public class RequestType
{
public RequestHeader Header { get; set; }
// ... other fields ...
}
[XmlRoot]
public class AnotherRequestType
{
public RequestHeader Header { get; set; }
// ... other fields ...
}
When serializing either of these types, the serializer encloses the contents of the Header
property in a <Header>
element. Is there an attribute that may decorate the Header
property such that the parent <Header>
element is not rendered? I've successfully accomplished this when serializing collection properties, but I wasn't sure if it could be done with a single element.
<RequestHeader>
<Header> <!-- omit this -->
<UserId>user</UserId>
<RequestId>123</RequestId>
</Header> <!-- omit this -->
</RequestHeader>
Alternatively, I can resort to inheritance or a collection with one element, but either of these options don't provide for a clean programming model.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想说您在
RequestHeader
类上实现IXmlSerialized
并使用 writer 手动编写属性,而不将它们包装在某些外部标记中。I would say you implement
IXmlSerializable
onRequestHeader
class and write attributes using writer manually, without wrapping them in some outer tag.为了跟进这个问题,我最终引入了一个基类来存储 XML 可序列化类型的公共元素。在扫描了控制 XML 序列化的属性集并且没有找到合适的机制之后,我得出的结论是,这似乎是解决重复问题的唯一机制。
To follow up on this question, I ended up introducing a base class to store the common elements of my XML-serializable types. After scanning the set of attributes that control XML-serializaion, and not finding a suitable mechanism, I concluded that this appears to be the only mechanism to solve the duplication issue.