【发布时间】:2011-02-09 13:35:01
【问题描述】:
我的问题似乎很奇怪,我没有发现任何其他问题,所以我想这是一个非常简单和愚蠢的错误,我似乎无法找出。
我有一个 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 变量,但我在类中的任何地方都没有看到该变量定义?
标签: c# attributes xmlserializer