XML Deserialize - Same element name different xsi:type. No need to validate

247 Views Asked by At

We extract thousands of XML-files from a source we can't control which have the same name but different xsi:type. We want to deserialize these XML to C# and we are generating this C# class from this XSD with xsd.exe.

I'm not sure if we are able to fix the XSD we generate from or if we need to handle the issue from another perspective (changing the generateted C# class, which is a mess, or add another layer somewhere).

From what I understand with XML 1.0 xsi:type can be used to achieve this wish xsi:type=" another-ns: ExportStatement" but this is not possible since I can't change the XML files.

The only difference between, from what I see, is that ExportStatement has two more elements:

<xsd:element name="Letter" type="xsd:string" minOccurs="0" />
<xsd:element name="No" type="xsd:string" minOccurs="0" />

Like I said, we only use the XSD to generate classes, we don't need to validate XML-files.

Here is a sample of the XML-file:

 <Phrase xsi:type="ExportPhrase" Id="114122" DiscriminatorId="292" SortOrder="0" PhraseField="0">
    <EuPhracPhraseId xsi:nil="true" />
    <AdditionalLocales />
    <MergePhrases />
    <Texts>
      <Text LocaleId="1">
        <Text><![CDATA[AData]]></Text>
      </Text>
      <Text LocaleId="2">
        <Text><![CDATA[BData]]></Text>
      </Text>
      <Text LocaleId="3">
        <Text><![CDATA[CData]]></Text>
      </Text>
      
    </Texts>
  </Phrase>
  <Phrase xsi:type="ExportStatement" Id="30010100" DiscriminatorId="1042" SortOrder="0" PhraseField="181">
    <EuPhracPhraseId xsi:nil="true" />
    <AdditionalLocales />
    <MergePhrases />
    <Letter>P</Letter>
    <No>101</No>
    <Texts>
      <Text LocaleId="1">
        <Text><![CDATA[EData]]></Text>
      </Text>
      <Text LocaleId="2">
        <Text><![CDATA[FData]]></Text>
      </Text>
      <Text LocaleId="3">
        <Text><![CDATA[GData]]></Text>
      </Text>
    </Texts>
  </Phrase>

Part of the XSD:

<xsd:element name="Phrases">
<xsd:complexType>
        <xsd:choice maxOccurs="unbounded">
            <xsd:element name="Phrase" type="ExportStatement" />
            <xsd:element name="Phrase" type="ExportPhrase" />
            <xsd:element name="ExportStatement" type="ExportStatement" />
        </xsd:choice>
</xsd:complexType>
</xsd:element>

XMLSerializer:

private static XMLDoc GetMaster(XmlSerializer xmlDocSerializer)
    {
        var masterFile = "XSD\\master.xml";
        TextReader masterReader = new StreamReader(masterFile, Encoding.Unicode);            
        var master = (XMLDoc)xmlDocSerializer.Deserialize(masterReader);
        return master;
0

There are 0 best solutions below