I have a class that I am not sure how to implement. Not sure how to instantiate and set the Quantity choice to a particular value. The serialization is not producing the desired output. I am trying to have the class serialized to output
<aaaa>
<Quantity>Quantity</Quantity>
</aaaa>
Where as I am expecting
<aaaa>
<Quantity>2</Quantity>
</aaaa>
public class aaaa {
private object itemField;
[System.Xml.Serialization.XmlElementAttribute("Available", typeof(bool))]
[System.Xml.Serialization.XmlElementAttribute("Lookup", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("Quantity", typeof(string), DataType="nonNegativeInteger")]
public object Item {
get {
return this.itemField;
}
set {
this.itemField = value;
}
}
}
private void myFunc()
{
try {
var myClass = new aaaa {
Item = "Quantity"
};
XmlSerializer serializer = new XmlSerializer(typeof(aaaa));
serializer.Serialize(stringwriter , Item);
} catch (Exception ex) {
}
}
And here is the XML from which the class was auto gen'd.
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xsd:element name="aaaa">
<xsd:complexType>
<xsd:sequence>
<xsd:choice>
<xsd:element name="Available" type="xsd:boolean"/>
<xsd:element name="Quantity" type="xsd:nonNegativeInteger"/>
<xsd:element name="Lookup" type="xsd:string"/>
</xsd:choice>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
CodePudding user response:
To get this desired output you would have to instantiate your class this way :
var aaaa = new aaaa();
aaaa.Item = "500";
aaaa.ItemElementName = ItemChoiceType.Quantity;
Then you would get this :
<aaaa xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Quantity>500</Quantity>
</aaaa>
Item contains the value of the element so you must make sure that the type of this object respect what's in these attributes :
[System.Xml.Serialization.XmlElementAttribute("Available", typeof(bool))]
[System.Xml.Serialization.XmlElementAttribute("Lookup", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("Quantity", typeof(string), DataType="nonNegativeInteger")]
As you can see Quantity is a string and not an actual integer, using an integer would not work.