如何序列化为XmlDocument/XmlElement以从WCF返回它?
我试图做的是从我的WCF服务返回如何序列化为XmlDocument/XmlElement以从WCF返回它?,xml,wcf,xml-serialization,wcf-data-services,Xml,Wcf,Xml Serialization,Wcf Data Services,我试图做的是从我的WCF服务返回XmlDocument 问题是我得到了一个错误“根元素丢失” 这是我的密码 public XmlElement GetDeviceListXML()// this got [XmlSerializerFormat]and [OperationContract] { List<Device> list = MyProject.BLL.Device.GetList();// here i getting list of de
XmlDocument
问题是我得到了一个错误“根元素丢失”
这是我的密码
public XmlElement GetDeviceListXML()// this got [XmlSerializerFormat]and [OperationContract]
{
List<Device> list = MyProject.BLL.Device.GetList();// here i getting list of devices from my database
//Device is object which got [serializable] attribute
XmlRootAttribute xra = new XmlRootAttribute("Device");
xra.ElementName = "Devices";
xra.Namespace = "http://MMEwidencja.pl";
xra.IsNullable = false;
XmlSerializer serializer = new XmlSerializer(typeof(List<Device>), xra);
var stream = new MemoryStream();
XmlDocument xDoc = new XmlDocument();;
try
{
serializer.Serialize(stream, list);
stream.Position = 0;// that what was I miss
xDoc.Load(stream);
}
catch (Exception ex)
{
throw ex;
}
return xDoc.DocumentElement;
}
public XmlElement GetDeviceListXML()//这得到了[XmlSerializerFormat]和[OperationContract]
{
List List=MyProject.BLL.Device.GetList();//这里我从数据库中获取设备列表
//设备是具有[serializable]属性的对象
XmlRootAttribute xra=新的XmlRootAttribute(“设备”);
xra.ElementName=“设备”;
xra.Namespace=”http://MMEwidencja.pl";
xra.IsNullable=false;
XmlSerializer serializer=新的XmlSerializer(typeof(List),xra);
var stream=newmemoryStream();
XmlDocument xDoc=新的XmlDocument();;
尝试
{
序列化(流,列表);
stream.Position=0;//我错过了什么
xDoc.负载(流);
}
捕获(例外情况除外)
{
掷骰子;
}
返回xDoc.DocumentElement;
}
我该怎么做
编辑:
我已经找到了解决方案,问题是XmlDocument试图将流从最后一个字节加载到最后一个字节。我没有在该流中将位置设置为0。没有根元素,因为XmlDocument.Load函数认为该流的长度为0字节
也许可以阅读以下链接:将xml作为文本流返回,然后将其加载到消费者的XmlDocument中,会更简洁 在去bug模式下,我的memorystream的长度为2653573字节,所以不是这个意思,我的意思是加载函数位于流的末尾,您需要将流放在位置0。Stream.position=0;如果可行,还应删除try/catch。它没有任何好处,并且将显示来自错误位置的异常。您还应该在流周围使用
using
块,以确保它得到处理。顺便问一下,如果您只是返回列表而不是首先序列化列表,会发生什么?WCF不会为您序列化它吗?