我有一个类,我不确定如何实现。不确定如何实例化并将Quantity选择设置为特定值。序列化没有产生期望的输出。我试图有类序列化输出
<aaaa>
<Quantity>Quantity</Quantity>
</aaaa>
Where as I looking
<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) {
}
}
这是自动生成类的XML。
<?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>
要获得所需的输出,您必须这样实例化您的类:
var aaaa = new aaaa();
aaaa.Item = "500";
aaaa.ItemElementName = ItemChoiceType.Quantity;
那么你会得到这个:
<aaaa xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Quantity>500</Quantity>
</aaaa>
Item包含元素的值,因此您必须确保该对象的类型遵循这些属性中的内容:
[System.Xml.Serialization.XmlElementAttribute("Available", typeof(bool))]
[System.Xml.Serialization.XmlElementAttribute("Lookup", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("Quantity", typeof(string), DataType="nonNegativeInteger")]
正如你所看到的,Quantity是一个字符串而不是一个实际的整数,使用整数是行不通的。