您可以简单地返回一个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(并且因此没有数据成员),因为我发回一个预定义的类(的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>
我有这本书在我面前...;) 把它从我的同事办公桌上删除... 感谢您的提示。 – GordonB 2009-06-01 15:06:34