我有一個我不知道如何實作的類。不確定如何實體化并將 Quantity 選項設定為特定值。序列化沒有產生所需的輸出。我正在嘗試將類序列化為輸出
<aaaa>
<Quantity>Quantity</Quantity>
</aaaa>
正如我所期待的那樣
<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>
uj5u.com熱心網友回復:
要獲得所需的輸出,您必須以這種方式實體化您的類:
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 是一個字串而不是一個實際的整數,使用整數是行不通的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/331662.html
下一篇:XMLSerializer例外“有一個錯誤反映欄位”和“對于非陣列型別,您可以使用以下屬性:XmlAttribute,..”
