1

I'm trying to expose a fairly complex object as XML through a REST API (using WCF).

However, the object is defined by an XSD file so I've generated classes using the xsd.exe tool. The problem is that it seems that when my object is serialized to XML, an attribute (defined in the xsd) is serialized into an element. And I don't get why. Currently, I'm assuming that my xsd somehow allows that, but I can't tell why. I don't do any custom serialization, I let the framework handle it.

Can someone explain why this is happening and how do I control the behavior?

Here the part from the xsd containing the element and attribute. Edit: the attribute in question is version

<xs:schema xmlns:b="http://some.namespace.com/" xmlns="http://someothernamespace.com/" elementFormDefault="qualified" targetNamespace="http://someothernamespace.com/" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:include schemaLocation="JobPositionPosting.xsd" />
  <xs:element name="Envelope">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="Sender" />
        <xs:element minOccurs="0" ref="TransactInfo" />
        <xs:element maxOccurs="unbounded" ref="Packet" />
      </xs:sequence>
      <xs:attribute fixed="0.52" name="version" type="xs:string" use="required" />
    </xs:complexType>
  </xs:element>

And here's the generated code.

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "<removed>")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://somenamespace.com", IsNullable = false)]
public partial class Envelope
{

    /// <remarks/>
    public Sender Sender;

    /// <remarks/>
    public TransactInfo TransactInfo;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Packet")]
    public Packet[] Packet;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute("version")]
    public string version;

    public Envelope()
    {
        this.version = "0.52";
    }
}

And here's the xml returned from the REST service, i.e. the serialized object.

<!-- (the rest o the xml is left out on purpose) -->
<Envelope>
    <senderField i:nil="true"/>
    <transactInfoField i:nil="true"/>
    <versionField>0.52</versionField>
</Envelope>

Thanks!

4

1 回答 1

0

xsd.exe生成要由 使用的类System.Xml.Serialization.XmlSerializer,而您的 REST 服务正在使用System.Runtime.Serialization.DataContractSerializer.

对于DataContractSerializer,您应该svcutil.exe改用。

svcutil.exe /help
svcutil.exe schema.xsd /dconly
于 2012-07-13T15:53:22.413 回答