我目前的任务是编写一个用于处理HL7 CDA文件的类库。这些HL7 CDA文件是带有定义的XML架构的XML文件,因此我使用了xsd.exe来为XML序列化和反序列化生成.NET类。
XML Schema包含各种类型,其中包含mixed="true"属性,指定此类型的XML节点可以包含普通文本与其他XML节点混合。
对于其中一种类型,XML模式的相关部分如下:
<xs:complexType name="StrucDoc.Paragraph" mixed="true">
<xs:sequence>
<xs:element name="caption" type="StrucDoc.Caption" minOccurs="0"/>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="br" type="StrucDoc.Br"/>
<xs:element name="sub" type="StrucDoc.Sub"/>
<xs:element name="sup" type="StrucDoc.Sup"/>
<!-- ...other possible nodes... -->
</xs:choice>
</xs:sequence>
<xs:attribute name="ID" type="xs:ID"/>
<!-- ...other attributes... -->
</xs:complexType>
此类型的生成代码如下:
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(TypeName="StrucDoc.Paragraph", Namespace="urn:hl7-org:v3")]
public partial class StrucDocParagraph {
private StrucDocCaption captionField;
private object[] itemsField;
private string[] textField;
private string idField;
// ...fields for other attributes...
/// <remarks/>
public StrucDocCaption caption {
get {
return this.captionField;
}
set {
this.captionField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("br", typeof(StrucDocBr))]
[System.Xml.Serialization.XmlElementAttribute("sub", typeof(StrucDocSub))]
[System.Xml.Serialization.XmlElementAttribute("sup", typeof(StrucDocSup))]
// ...other possible nodes...
public object[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string[] Text {
get {
return this.textField;
}
set {
this.textField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType="ID")]
public string ID {
get {
return this.idField;
}
set {
this.idField = value;
}
}
// ...properties for other attributes...
}
如果我对一个XML元素进行反序列化,其中段落节点看起来像这样:
<paragraph>first line<br /><br />third line</paragraph>
结果是,项目和文本数组的读取方式如下:
itemsField = new object[]
{
new StrucDocBr(),
new StrucDocBr(),
};
textField = new string[]
{
"first line",
"third line",
};
从这里无法确定文本和其他节点的确切顺序。
如果我再次进行序列化,结果看起来与此完全相同:
<paragraph>
<br />
<br />first linethird line
</paragraph>
默认的序列化器只是先序列化项目,然后再序列化文本。我尝试在 StrucDocParagraph 类上实现 IXmlSerializable,以便我可以控制内容的反序列化和序列化,但由于涉及到许多类,所以它相当复杂,并且我还没有找到解决方案,因为我不知道这样做是否值得。
有没有一种容易的解决方法来解决这个问题,或者通过 IXmlSerializable 进行自定义序列化甚至可能吗? 还是我应该使用 XmlDocument 或 XmlReader/XmlWriter 来处理这些文档?