views:

110

answers:

2

I have an element that can have multiple types (not my design). The element itself is a complex type with a sequence of sub-elements and the XML is generated from the serialization of a property, and that property returns a type of base class. So when the XML is generated the type ends up getting set in the XML to whatever the object really was. For example:

      <Answer xsi:type="AnswerBool">
        <Value xsi:type="xsd:int">-1</Value>
      </Answer>

Or it might be:

      <Answer xsi:type="AnswerString">
        <Value xsi:type="xsd:string">-1</Value>
      </Answer>

The C# property looks like this:

    public AnswerBase Answer
    {
        get { return mViewAnswer; }
        set { mViewAnswer = value; }
    }

So if the variable nViewAnswer is of type AnswerBool then the first XML example is generated when serialized. If it is of type AnswerString then the second XML examle is generated.

So I've been working on some sort of XSD for the XML. However, when it comes to validation I cannot seem to get this to work. Obviously one option would be to alter how the XML is structured and have sub-elements of the "Answer" element. However, that would require a re-working of existing functionality that I'd prefer to avoid if possible. So....

Is there any way to have an element have different types defined in the schema?

Or is there any way to have the XSD set up so that it ignores the xsi:type for that element during validation? I've been fiddling with anyAttribute processContents but I do not believe that will help.

Am I going to be stuck re-working how the XML is formed?

A: 

Check this post which if nothing else will point you to some further reading.

It may not be so bad to rework the xml if you consider doing a transformation. Usually you are stuck with the problematic xml for a reason, i.e. some existing system exports it that way. A transformation using xslt, would let you keep the legacy xml and also have it in the new format for validation against a new schema. The double bonus is that you know the transformed xml is valid.

Mark Dickinson
Thanks for the link. I almost have it working.
Eves
+1  A: 

I have been unable to get my XML to work with any form of schema I've tried. It looked like I almost had it with the whole thing about generating my own "type" attribute but ultimately I the fact that my XML had:

      <Answer xsi:type="AnswerBool">
        <Value xsi:type="xsd:int">-1</Value>
      </Answer>

I was unable to handle the "xsi:" part of the "type" since my attribute was merely only "type" and therefore would not match with "xsi:type". My schema instances were all the same so I do not know why there was a problem.

So I'll be changing things so that I will no longer have a single "Answer" element. I will have a few dozen different elements, one for each type. Bummer.

Thanks for the help Mark.

Eves