XML将列表对象序列化为从XSD文件生成的XmlText(XmlTextAttribute)

时间:2014-02-28 13:58:19

标签: c# xml serialization xsd

我在序列化对象时遇到问题。该对象是从XSD文件生成的。

这是XSD中的元素:

<xs:element name="ResGuestRPHs" type="ResGuestRPHsType" minOccurs="0">
    <xs:annotation>
        <xs:documentation xml:lang="en">A collection of ResGuestRPH objects. </xs:documentation>
    </xs:annotation>
</xs:element>

<xs:complexType name="ResGuestRPHsType">
    <xs:annotation>
        <xs:documentation xml:lang="en">A collection of unsigned integers serving as reference placeholders, and used as an index identifying which guests occupy this room</xs:documentation>
    </xs:annotation>
    <xs:simpleContent>
        <xs:extension base="ListOfRPH"/>
    </xs:simpleContent>
</xs:complexType>

<xs:simpleType name="ListOfRPH">
    <xs:annotation>
        <xs:documentation xml:lang="en">List of Reference Place Holders.</xs:documentation>
    </xs:annotation>
    <xs:list itemType="RPH_Type"/>
</xs:simpleType>

<xs:simpleType name="RPH_Type">
    <xs:annotation>
        <xs:documentation xml:lang="en">The Reference Place Holder (RPH) is an index code used to identify an instance in a collection of like items (e.g. used to assign individual passengers or clients to particular itinerary items).</xs:documentation>
    </xs:annotation>
    <xs:restriction base="xs:string">
        <xs:pattern value="[0-9]{1,8}"/>
    </xs:restriction>
</xs:simpleType>

此元素应在序列化后输出为(注意数字之间的空格以指示它是列表的2个元素):

<ResGuestRPHs>1 2</ResGuestRPHs>

但它是否在没有空间的情况下生成导致反序列化为仅1个元素:

<ResGuestRPHs>12</ResGuestRPHs>

这是生成的对象:

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.18408")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.opentravel.org/OTA/2003/05")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://www.opentravel.org/OTA/2003/05", IsNullable=true)]
public partial class ResGuestRPHsType
{

    private System.Collections.Generic.List<string> textField;

    /// <remarks/>
    [System.Xml.Serialization.XmlTextAttribute()]
    public System.Collections.Generic.List<string> Text
    {
        get
        {
            return this.textField;
        }
        set
        {
            this.textField = value;
        }
    }
}

这是使用“WSCF.blue”生成的。当我将List更改为数组时,它会出现同样的问题。当我使用它作为“XmlAttributeAttribute”是有效的(但它没有与XSD ofcourse验证)。

有人知道为什么这不能正确序列化吗?

1 个答案:

答案 0 :(得分:0)

目前我使用以下“脏”解决方案。添加到列表时,我手动添加一个空格(resGuestRPH是要添加的变量):

ResGuestRPHs.Text.Add(resGuestRPH + " ");

阅读列表时,我手动拆分字符串:

ResGuestRPHs.Text = ResGuestRPHs.Text.First().Trim().Split(' ').ToList();

这样XML就可以通过XSD验证,但我仍然希望有人能帮我找到一个“干净”的解决方案。