我的問題似乎很奇怪,我沒有發現任何其他問題,所以我想這是一個非常簡單和愚蠢的錯誤,我無法找出答案。C#XmlSerializer忽略xs:屬性,其類型不是xs:字符串
我有一個XSD,從中我使用xsd.exe生成一個類結構。我用值「填充」我的對象,但是當將它序列化爲XML時,它會忽略所有類型不屬於string
類型的屬性。
var myGraph = new graph();
myGraph.myString = "hallo";
myGraph.myInt = 80;
var serializer = new XmlSerializer(typeof(graph));
TextWriter writeFileStream = new StreamWriter(Path.Combine(outFolder, outFile));
serializer.Serialize(writeFileStream, myGraph);
writeFileStream.Close();
我預計:
<graph xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
myString="hallo"
myInt="80"
/>
實際的輸出是:
<graph xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
myString="hallo"
/>
屬性myInt
已被忽略。如果我將它定義爲一個字符串,它也會出現,但是和其他類型一樣,它不會顯示出來。如果我聲明required
並將其保留null
,它將被序列化爲myInt="0"
。
我錯過了什麼?
一些細節:
XSD:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="graph">
<xs:complexType>
<xs:attribute name="myString" type="xs:string" />
<xs:attribute name="myInt" type="xs:int" />
</xs:complexType>
</xs:element>
</xs:schema>
生成類:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=false)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class graph {
private string myStringField;
private int myIntField;
[System.Xml.Serialization.XmlAttributeAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified)]
public string myString {
get { return this.myStringField; }
set { this.myStringField = value; }
}
[System.Xml.Serialization.XmlAttributeAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified)]
public int myInt {
get { return this.myIntField; }
set { this.myIntField = value; }
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool myIntSpecified {
get { return this.myIntFieldSpecified; }
set { this.myIntFieldSpecified = value; }
}
在您發佈的生成的類中,myIntSpecified函數引用myIntFieldSpecified變量,但我沒有看到任何地方類定義這個變量? – pmartin 2011-02-09 14:08:08