Reputation: 690
I'm trying to deserialize a xml into a class but it's giving me an exception.
My class is something like that:
public class FieldsVO
{
public bool AllowPrint { get; set; }
public bool AllowAbort { get; set; }
public bool AllowPrintFSFSDA { get; set; }
}
And my XML:
<fields>
<AllowPrint>True</AllowPrint>
<AllowAbort>True</AllowAbort>
<AllowPrintFSFSDA>True</AllowPrintFSFSDA>
</fields>
The only way that the deserialization works is if the attributes are "string". There is any way to do it with anotations or something?
Here's the deserialization code:
public static object Deserialize(string xml, Type objType)
{
if (false == xml.StartsWith("<"))
{
int pos = xml.IndexOf('<');
xml = xml.Remove(0, pos);
}
XmlSerializer serializer = new XmlSerializer(objType);
XmlReaderSettings set = new XmlReaderSettings();
set.ValidationFlags = XmlSchemaValidationFlags.AllowXmlAttributes;
using (XmlReader reader = XmlReader.Create(new StringReader(xml), set))
return serializer.Deserialize(reader);
}
Upvotes: 1
Views: 466
Reputation: 330
When you want to parse XML, you should use XSD Schema.
XSD Schema describes a XML file.
For add this file: create an element -> XML Schema. Call this file fields.xsd.
In your case, it will be:
<xs:element name="fields">
<xs:complexType>
<xs:sequence>
<xs:element name="AllowPrint" type="xs:boolean"/>
<xs:element name="AllowAbort" type="xs:boolean"/>
<xs:element name="AllowPrintFSFSDA" type="xs:boolean"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Then, open the command-line interface. go to the directory where the fields.xsd is. enter:
xsd fields.xsd /classes
fields.cs is now generate.
In your XML file, you have to add: - the namespace of the XSD Schema - the location of the XSD Schema
xmlns="urn:fields"
xsi:schemaLocation="urn:fields fields.xsd">
Upvotes: 2