2014-05-23 15 views
0

我試圖轉換使用XML:在特殊字符的XSL上使用XSLTCompiledTransform?

private string transformXML(string xml_data, string xml_style) 
    { 
     //generemos un html temporal para mostrar la transformacion 
     string outfile = Path.GetTempFileName().Replace(".tmp", ".html"); 

     XslCompiledTransform proc = new XslCompiledTransform(); 

     using (System.IO.StringReader sr = new System.IO.StringReader(xml_style)) 
     { 
      using (XmlReader xr = XmlReader.Create(sr)) 
      { 
       proc.Load(xr); 
      } 
     } 

     string resultXML; 

     using (System.IO.StringReader sr = new System.IO.StringReader(xml_data)) 
     { 
      using (XmlReader xr = XmlReader.Create(sr)) 
      { 
       using (System.IO.StringWriter sw = new System.IO.StringWriter()) 
       { 
        proc.Transform(xr, null, sw); 
        resultXML = sw.ToString(); 
        System.IO.File.WriteAllText(outfile, resultXML); 

        return outfile; 
       } 
      } 
     } 
    } 

利用這一點,我上線porc.Load(xr)得到一個System.Xml.Xsl.XslLoadException,由於非法'<'。非法字符在該行的<

<xsl:when test="$value &lt; 19"> 

是,如你所見,逃過一劫。可能,Xml.Create()正在回顧我的<,這是怎麼回事?

回答

1

尊敬的:我建議這可能與您的方法的調用者中的編碼/解碼問題有關 - 例如XSL從源文件加載/傳遞到「 transformXML「方法。

審查關於這個我的想法我做了以下內容:

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Xml; 
using System.Xml.Xsl; 

namespace XSLPlayPlace 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string stylesheetText = File.ReadAllText("stylesheet.xsl"); 

      var program = 
       new Program().transformXML("<data><item>1</item><item>2</item><item>19</item><item>1</item></data>", stylesheetText); 
     } 

     private string transformXML(string xml_data, string xml_style) 
     { 
      [... snip ... your code copied exactly as per the question ...] 
     } 
    } 
} 

,並添加了文件到控制檯應用程序,將其設置爲「複製總是」該文件內容如下(隨機XSL塗鴉只是獲得XSL節點周圍的語法OK,你有一個問題關於):

<?xml version="1.0"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template name="test" match="//data/item"> 
    <xsl:variable name="value" select=". + 1"/> 
    <xsl:choose> 
     <xsl:when test="$value &lt; 19"> 
     </xsl:when> 
    </xsl:choose> 
    </xsl:template> 
</xsl:stylesheet> 

我很高興,這並不正確匹配,不打任何節點或返回任何值...但它確實證明XSL編譯得很好。

如果你調試你的代碼時要非常小心調試器如何顯示你已經傳入的XSL - >使用QuickWatch中的「上下文菜單」中的文本可視化器?可能會說明問題。

+0

它從臨時文件加載,該文件具有正確的'<'字符。我使用System.IO.File.ReadAllText(outfile)將它加載到一個字符串上,你認爲這可能是它? – jlasarte

+0

我不這麼認爲:因爲System.IO.File.ReadAllText()是我在上面的例子中使用的,並且工作正常。我將逐個構建XSL文件,直到它調用proc.Load(xr)爲止。 – Aidanapword

+0

是的,我注意到添加評論後。那麼,我會嘗試你的建議。 – jlasarte