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 something like:
<?xml version="1.0"?>
<Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<TextBox Name="abc" />
</Document>
Any ideas how to fix the xsd or another code generator?
Thanks.