Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以将xml转换处理指令添加到从wcf服务契约返回的xml中吗_Xml_Wcf_Stylesheet - Fatal编程技术网

我可以将xml转换处理指令添加到从wcf服务契约返回的xml中吗

我可以将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的restful wcf服务。我的想法是向xml中添加xsl转换处理指令,以便在通过web浏览器查看时使用数据

任务目标#1:
添加到返回的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;
    }
}