Hi,
I've been trying to create an XML document and corresponding XSD schema in C#.
I can create the XML fine and get the XSD, but the XSD isn't 100% correct.
The attribute type for my elements is always xs:string in the XSD, which is not correct.
Some of them need to be integer and others string.
I'm new to this so the answer might be pretty obvious but I'm just not sure how I go about doing it. I think I need to use XmlSerializer for it from what I have read but I'm not sure where to start with it.
Below of a a simple example of what I am trying to do:
class Person
{
public int ID { get; set; }
public String Name { get; set; }
public int Age { get; set; }
public XElement GetXML()
{
var person = new XElement("Person", new XAttribute("ID", ID));
person.Add(new XElement("Name", Name));
person.Add(new XElement("Age", Age));
return person;
}
}
static void Main(string[] args)
{
var set = new DataSet("Test");
var root = new XElement("root");
var p1 = new Person() {ID = 1, Name = "P1", Age = 32};
var p2 = new Person() {ID = 2, Name = "P2", Age = 40};
root.Add(p1.GetXML());
root.Add(p2.GetXML());
set.ReadXml(root.CreateReader());
var xml = set.GetXml();
var schema = set.GetXmlSchema();
Console.WriteLine(schema);
Console.WriteLine(xml);
Console.ReadKey(true);
}
This code produces the following XSD and XML
="1.0"="utf-16"
<xs:schema id="root" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:
msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="root" msdata:IsDataSet="true" msdata:Locale="en-US">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="Person">
<xs:complexType>
<xs:sequence>
<xs:element name="Name" type="xs:string" minOccurs="0" msdata:Ordinal="0" />
<xs:element name="Age" type="xs:string" minOccurs="0" msdata:Ordinal="1" />
</xs:sequence>
<xs:attribute name="ID" type="xs:string" />
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<root>
<Person ID="1">
<Name>P1</Name>
<Age>32</Age>
</Person>
<Person ID="2">
<Name>P2</Name>
<Age>40</Age>
</Person>
</root>
As you can see, in the XSD the Age element is given a type of string. I assume this is by default, but I cannot see how I am supposed to set this to a different type, such as integer.
Any help would be appreciated.
Thanks