Recursive XSD Help

Posted by Alon on Stack Overflow See other posts from Stack Overflow or by Alon
Published on 2010-04-11T15:10:49Z Indexed on 2010/04/11 15:13 UTC
Read the original article Hit count: 322

Filed under:
|
|
|
|

Hi, i'm trying to learn a little bit XSD and I'm trying to create a XSD for this xml:

<Document>
  <TextBox Name="Username" />
  <TextBox Name="Password" />
</Document>

... so there's an element, which is an abstract complex type. Every element have elements and so on. Document and TextBox are extending Element.

I trid this:

<?xml version="1.0" encoding="utf-8" ?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Document">
    <xs:complexType>
      <xs:complexContent>
        <xs:extension base="Element">

        </xs:extension>
      </xs:complexContent>
    </xs:complexType>
  </xs:element>

  <xs:complexType name="Element" abstract="true">
    <xs:sequence minOccurs="0" maxOccurs="unbounded">
      <xs:element name="Element" type="Element"></xs:element>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="TextBox">
    <xs:complexContent>
      <xs:extension base="Element">
        <xs:attribute name="Name" type="xs:string" />
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>
</xs:schema>

I compiled it to C# with Xsd2Code, and now I try to deserialize it:

var serializer = new XmlSerializer(typeof(Document));

var document = (Document)serializer.Deserialize(new FileStream("Document1.xml", FileMode.Open));

foreach (var element in document.Element1)
{
    Console.WriteLine(((TextBox)element).Name);
}

Console.ReadLine();

and it dosen't print anything. When I try to serialize it like so:

var serializer = new XmlSerializer(typeof(Document));

var document = new Document();

document.Element1 = new List<Element>();

document.Element1.Add(new TextBox()
{
    Name = "abc"
});

serializer.Serialize(new FileStream("d.xml", FileMode.Create), document);

...the output is:

<?xml version="1.0"?>
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Element1>
    <Element xsi:type="TextBox">
      <Element1 />
      <Name>abc</Name>
    </Element>
  </Element1>
</Document>

When it should be:

<Document>
  <TextBox Name="abc" />
</Document>

Any ideas how to fix the xsd or another code generator?

Thanks.

© Stack Overflow or respective owner

Related posts about Xml

Related posts about xsd