WCF序列化与预期不符

时间:2012-09-19 22:58:16

标签: c# asp.net wcf web-services xml-serialization

我有一个像这样的c#类作为我的WCF方法的返回:

[Serializable]
[XmlRoot("OutputItem")]
public class MyItem
{
    [XmlElement("ItemName")] 
    public string NodeName { get; set; }

    [XmlArray("Fields"), XmlArrayItem(ElementName = "Field", Type = typeof(MyItemField))]
    public List<MyItemField> Fields { get; set; }

}

我的WCF方法是这样的:

public MyItem GetItemXML(string id)
{
   MyItem mi = new MyItem();

   //do some stuff to populate mi

   return mi;   
}

我希望这个的XML输出是这样的:

<xml version="1.0" encoding="utf-16"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <GetItemXMLResponse xmlns="http://www.here.com/XML/ItemService.xsd">
      <GetItemXMLResult>
        <OutputItem>
           <ItemName>FR</ItemName>
           <Fields>
            ......
           </Fields>
        </OutputItem>
      </GetItemXMLResult>
    </GetItemXMLResponse>
  </s:Body>
</s:Envelope>

但是,输出的输出如下 - 顶部没有<OutputItem>指令:

<xml version="1.0" encoding="utf-16"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <GetItemXMLResponse xmlns="http://www.here.com/XML/ItemService.xsd">
      <GetItemXMLResult>
           <ItemName>FR</ItemName>
           <Fields>
            ......
           </Fields>
      </GetItemXMLResult>
    </GetItemXMLResponse>
  </s:Body>
</s:Envelope>

我错过了什么?

2 个答案:

答案 0 :(得分:0)

如果我没记错的话,一切都取决于你的[OperationContract]的定义方式。您可能必须使用消息合同来获得所需的行为。看看http://msdn.microsoft.com/en-us/library/ms730255.aspx

答案 1 :(得分:0)

// The Model Object

[Serializable]
[XmlRoot("OutputItem")]
[DataContractAttribute]
public class MyObject
{
    [XmlElement("ItemName")]
    [DataMemberAttribute] 
    public string Name { get; set; }

    [XmlArray("DummyItems")]
    [XmlArrayItem("DummyItem", typeof(MyItemField))]
    public List<Fields> DummyItem { get; set; }
}



// The Class that implement the contract
[DataContract]
public class ConsumptionService : IAnyContract
{
    public MyObject GetItemXML(string id)
    {
       MyObject mo = new MyObject();
       //do some stuff to populate mi
       MyObject mo;   
    }
 }