您可以简单地返回一个 XmlElement - 可能是 XmlDocument 实例的 DocumentElement 属性。
您不必use the XmlSerializer to do this。 DataContractSerializer 是默认值,并且会很好地发回 XmlElement。您不需要实现 IXmlSerializable。
下面是一些示例代码
服务接口:
using System;
using System.Xml;
using System.ServiceModel;
using System.Runtime.Serialization;
namespace Cheeso.Samples.Webservices
{
[ServiceContract(Namespace="urn:Cheeso.Samples" )]
public interface IService
{
[OperationContract]
XmlElement Register(String request);
}
}
请注意,我没有 DataContract(因此也没有 DataMembers),因为我正在发回一个预定义类 (XmlElement) 的实例。
这是服务实现:
using System;
using System.Xml;
using System.ServiceModel;
namespace Cheeso.Samples.Webservices._2009Jun01
{
public class Results
{
public int Id;
public Int64 WorkingSet;
public String Name;
public String Title;
}
[ServiceBehavior(Name="WcfXmlElementService",
Namespace="urn:Cheeso.Samples",
IncludeExceptionDetailInFaults=true)]
public class WcfXmlElementService : IService
{
int index = 0;
public XmlElement Register(string request)
{
XmlDocument doc = new XmlDocument();
// can get the doc from anywhere. We use a LINQ-to-Objects result.
// do the LINQ thing
var processInfo =
from p in System.Diagnostics.Process.GetProcesses()
select new Results {
Id = p.Id,
WorkingSet = p.WorkingSet64,
Name = p.ProcessName,
Title = p.MainWindowTitle
};
// Note: cannot use an anonymous ilist if we will use XmlSerializer
// serialize that list into the XmlDocument
using (XmlWriter writer = doc.CreateNavigator().AppendChild())
{
var L = processInfo.ToList();
XmlSerializer s1 = new XmlSerializer(L.GetType());
s1.Serialize(writer, L);
}
index++;
// Append some additional elements to the in-memory document.
XmlElement elem = doc.CreateElement("id");
elem.InnerText = System.Guid.NewGuid().ToString();
doc.DocumentElement.AppendChild(elem);
elem = doc.CreateElement("stamp");
elem.InnerText = DateTime.Now.ToString("G");
doc.DocumentElement.AppendChild(elem);
elem = doc.CreateElement("in-reply-to");
elem.InnerText = request;
doc.DocumentElement.AppendChild(elem);
return doc.DocumentElement;
}
}
}
如果您使用的是 .NET,客户端会获取一个 XmlElement。如果您使用的是其他堆栈,则它将只是该堆栈中的 XmlElement 或 XmlNode。
回复消息的 XSD 是通用的,如下所示:
<xs:element name="RegisterResponse">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" name="RegisterResult" nillable="true">
<xs:complexType>
<xs:sequence>
<xs:any minOccurs="0" processContents="lax" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>