我可以将xml转换处理指令添加到从wcf服务契约返回的xml中吗
我有一个返回xml的restful wcf服务。我的想法是向xml中添加xsl转换处理指令,以便在通过web浏览器查看时使用数据 任务目标#1:我可以将xml转换处理指令添加到从wcf服务契约返回的xml中吗,xml,wcf,stylesheet,Xml,Wcf,Stylesheet,我有一个返回xml的restful wcf服务。我的想法是向xml中添加xsl转换处理指令,以便在通过web浏览器查看时使用数据 任务目标#1: 添加到返回的xml 我尝试了以下方法; 向xml文档中添加xml样式表标记的推荐方法似乎是WriteProcessingInstruction方法,但是System.xml.XmlDictionaryWriter不允许对WriteProcessingInstruction(字符串名称,字符串文本)进行任何调用,其名称参数不是“xml”WriteRaw,
添加到返回的xml
我尝试了以下方法;
向xml文档中添加xml样式表标记的推荐方法似乎是WriteProcessingInstruction
方法,但是System.xml.XmlDictionaryWriter
不允许对WriteProcessingInstruction(字符串名称,字符串文本)
进行任何调用,其名称参数不是“xml”<也不允许使用code>WriteRaw,因为它只能在xml根节点内写入数据
有没有办法将xml样式表标记附加到从wcf服务返回的xml上?我通过实现自己的XmlWriter来完成这项工作,XmlWriter编写处理指令。(在我的示例中,仅适用于选定名称空间中的响应): 当然,在典型的WCF方式中,最困难的部分是让WCF使用它。对我来说,这涉及:
- 实现自定义WebServiceHost和WebServiceHostFactory
- 将ServiceEndpoints的WebMessageEncodingBindingElement替换为自定义MessageEncodingBindingElement
- 重写MessageEncodingBindingElement.CreateMessageEncoderFactory以返回自定义MessageEncoderFactory
- 实现在编码器属性上返回自定义MessageEncoder的自定义MessageEncoderFactory
- 实现在WriteMessage实现中使用样式表XmlTextWriter的自定义MessageEncoder
public class StylesheetXmlTextWriter : XmlTextWriter
{
private readonly string _filename;
private readonly string[] _namespaces;
private bool firstElement = true;
public StylesheetXmlTextWriter(Stream stream, Encoding encoding, string filename, params string[] namespaces) : base(stream, encoding)
{
_filename = filename;
_namespaces = namespaces;
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
if (firstElement && (_namespaces.Length == 0 || _namespaces.Contains(ns)))
WriteProcessingInstruction("xml-stylesheet", string.Format("type=\"text/xsl\" href=\"{0}\"", _filename));
base.WriteStartElement(prefix, localName, ns);
firstElement = false;
}
}