C#XmlSerializer使用xs:string以外的类型忽略xs:attribute

Jan*_*Jan 1 c# attributes xmlserializer

我的问题似乎很奇怪,我没有发现任何其他问题,所以我想这是一个非常简单和愚蠢的错误,我似乎无法找到.

我有一个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();
Run Code Online (Sandbox Code Playgroud)

我期望:

<graph xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"  
    myString="hallo" 
    myInt="80"
/>
Run Code Online (Sandbox Code Playgroud)

实际输出是:

<graph xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    myString="hallo" 
/>
Run Code Online (Sandbox Code Playgroud)

该属性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>
Run Code Online (Sandbox Code Playgroud)

生成的类:

[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; }
    }
Run Code Online (Sandbox Code Playgroud)

pma*_*tin 7

XSD将为值类型的所有属性添加额外的"指定"字段.使用带有值类型的.NET序列化时,您始终需要指定字段的值并将匹配的"specified"属性设置为true.

将代码更改为此代码,它将按预期工作:

var myGraph = new graph();
myGraph.myString = "hallo";
myGraph.myInt = 80;
myGraph.myIntSpecified = true;
Run Code Online (Sandbox Code Playgroud)