Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Complex types with xs:any / ##any and mixed in code generated by the XSD tool

I have the following complex type in my XML schema:

<xs:complexType name="Widget" mixed="true">
    <xs:sequence>
        <xs:any namespace="##any" processContents="skip" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
</xs:complexType>

The element in derived XML could contain string or could contained wellformed XML, hence the mixed attribute being true.

When I run this through the .NET XSD Tool I get the following generate code:

public partial class Widget{

    private System.Xml.XmlNode[] anyField;

    /// <remarks/>
    [System.Xml.Serialization.XmlTextAttribute()]
    [System.Xml.Serialization.XmlAnyElementAttribute()]
    public System.Xml.XmlNode[] Any {
        get {
            return this.anyField;
        }
        set {
            this.anyField = value;
        }
    }
}

The question I have is that I am not entirely sure how I should then use this. Ultimately I need to be able to set the value of widget to either:

<widget>Hello World!</widget>

or

<widget>
  <foo>Hello World</foo>
</widget>

Both of which validate agaisnt the schema

like image 617
MrEyes Avatar asked Feb 11 '11 13:02

MrEyes


1 Answers

For this:

<widget>  
    <foo>Hello World</foo>
</widget>

Use this:

XmlDocument dom = new XmlDocument();
Widget xmlWidget = new Widget();
xmlWidget.Any = new XmlNode[1];
xmlWidget.Any[0] = dom.CreateNode(XmlNodeType.Element, "foo", dom.NamespaceURI);
xmlWidget.Any[0].InnerText = "Hello World!";

For this:

<widget>Hello World!</widget>

Use this:

XmlDocument dom = new XmlDocument();
XmlNode node = dom.CreateNode(XmlNodeType.Element, "foo", dom.NamespaceURI);
node.InnerText = "Hello World";

Widget w = new Widget();
w.Any = new XmlNode[1];
w.Any[0] = node.FirstChild; 
like image 74
pmartin Avatar answered Nov 09 '22 09:11

pmartin