问题
I have created an XSD file from Visual Studio 2010,
Then I use xsd /c mydemo.xsd
to generate class for me, so that I can create a XML file at runtime.
However, when I use that class, fill in some values, and serialize the object, the XML file does not look nice to me.
Here is my XSD file Click here to see
What I expected the XML file to be is Click here to see (Generated from Visual Studio "Sample XML")
But when I try to serialize it, the XML file is like this CLick here to see
The format is totally different
e.g
Expecting:
<ColumnInfo>
<Column Type="Type1" DisplayValue="DisplayValue1" Key="Key1"/>
<Column Type="Type2" DisplayValue="DisplayValue2" Key="Key2"/>
<Column Type="Type3" DisplayValue="DisplayValue3" Key="Key3"/>
</ColumnInfo>
but the generate result is like this:
<columnInfoField>
<ColumnType>
<displayValueField>Display value for key 1</displayValueField>
<keyField>key1</keyField>
<typeField>string</typeField>
</ColumnType>
<ColumnType>
<displayValueField>Display value for key 2</displayValueField>
<keyField>key2</keyField>
<typeField>int</typeField>
</ColumnType>
<ColumnType>
<displayValueField>Display value for key 3</displayValueField>
<keyField>key3</keyField>
<typeField>long</typeField>
</ColumnType>
</columnInfoField>
And the code I implement to serialize the report is :
http://msdn.microsoft.com/en-us/library/ms731073.aspx
DataContractSerializer dcs = new DataContractSerializer(typeof(Report));
using (XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateTextWriter(File.Create(@"C:\demo\schema\output.xml"), Encoding.UTF8))
{
dcs.WriteObject(xdw, report);
}
Not sure why I cannot use "XmlSerializer", when I use it, it will complain about cannot cast array type something...
Unable to generate a temporary class (result=1).
error CS0030: Cannot convert type 'ColumnValueType[]' to 'ColumnValueType'
error CS0029: Cannot implicitly convert type 'ColumnValueType' to 'ColumnValueType[]'
So, does anyone can give me some suggestion, how can i fix my XML format???
回答1:
There is a bug on xsd.exe - look at this blog-post: http://satov.blogspot.com/2006/12/xsdexe-generated-classes-causing.html
回答2:
The data contract serializer has different rules that the XmlSerializer. Why don't you try the XmlSerializer first and then see if the output is "correct".
来源:https://stackoverflow.com/questions/6038960/how-to-ask-xsd-exe-to-generate-proper-class-for-me-so-that-i-can-create-a-fine