artplastika
artplastika

Reputation: 1982

Deserializing complex element content to a string with XmlSerializer in C#

Is there any way to deserialize elements containing either simple text or subelement to a string with XmlSerializer?

Xml sample:

<Attribute>
    <AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">thisistext</AttributeValue>
    <AttributeValue>
        <e:Authorities xmlns:e="urn:dummy">
            <e:Authority>ORG_CHIEF</esia-encoder:Authority>
        </e:Authorities>
    </AttributeValue>
</Attribute>

C# property:

[XmlElement("AttributeValue", IsNullable = true)]
public string[] AttributeValue { get; set; }

Deserialization of the first AttributeValue succeed, but the next one fails. No wonder, beacause ReadElementString method expects simple or empty content. I'm looking for a way to tell to serializer "put content of this element to a string, whatever it contains".

Upvotes: 1

Views: 400

Answers (2)

StampedeXV
StampedeXV

Reputation: 2805

If you are able to define it in XSD, you can use XSD2Code or xsd.exe to create a class for the XSD to deserialize into.

What about this one?

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:element name="Attribute">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="AttributeValue" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:choice>
                            <xs:element name="AuthoritiesString" type="xs:string"/>
                            <xs:element name="AuthoritiesElement">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element name="Authority"/>
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                        </xs:choice>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

Upvotes: 0

Myrtle
Myrtle

Reputation: 5831

Actually, the 2nd value you have in your XML is:

 <e:Authorities xmlns:e="urn:dummy">
     <e:Authority>ORG_CHIEF</esia-encoder:Authority>
 </e:Authorities>

This is no valid string dataType which is expected because of:

public string[] AttributeValue {get; set;}

Upvotes: 1

Related Questions