2008-11-07 202 views
10

我試圖將一些Xaml轉換爲使用.NET XslCompiledTransform的HTML,並且遇到了使xslt與Xaml標籤匹配的困難。例如與此XAML輸入:xsl:模板匹配找不到匹配

<FlowDocument PagePadding="5,0,5,0" AllowDrop="True" NumberSubstitution.CultureSource="User" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> 
    <Paragraph>a</Paragraph> 
</FlowDocument> 

而這個XSLT:

<?xml version="1.0" encoding="utf-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" 
> 

    <xsl:output method="html" indent="yes"/> 

    <xsl:template match="/"> 
    <html> 
     <body> 
     <xsl:apply-templates /> 
     </body> 
    </html> 
    </xsl:template> 

    <xsl:template match="FlowDocument"> 
    <xsl:apply-templates /> 
    </xsl:template> 

    <xsl:template match="Paragraph" > 
    <p> 
     <xsl:apply-templates /> 
    </p> 
    </xsl:template> 

我得到這樣的輸出:

<html> 
    <body> 
    a 
</body> 
</html> 

低於預期的相反:

<html> 
    <body> 
     <p>a</p> 
    </body> 
</html> 

莫非這是名稱空間的問題?這是我第一次嘗試xsl轉換,所以我不知所措。

回答

20

是的,這是命名空間的問題。輸入文檔中的所有元素都在命名空間http://schemas.microsoft.com/winfx/2006/xaml/presentation中。您的模板試圖匹配默認命名空間中的元素,但它沒有找到任何元素。

您需要在變換中聲明此名稱空間,爲其分配一個前綴,然後在用於匹配該名稱空間中元素的任何模式中使用該前綴。所以,你應該XSLT看起來是這樣的:

<?xml version="1.0" encoding="utf-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" 
    xmlns:p="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    exclude-result-prefixes="msxsl"/> 

<xsl:output method="html" indent="yes"/> 

<xsl:template match="/"> 
    <html> 
    <body> 
     <xsl:apply-templates /> 
    </body> 
    </html> 
</xsl:template> 

<xsl:template match="p:FlowDocument"> 
    <xsl:apply-templates /> 
</xsl:template> 

<xsl:template match="p:Paragraph" > 
    <p> 
    <xsl:apply-templates /> 
    </p> 
</xsl:template> 
+0

Thanks Robert - 我曾嘗試將名稱空間添加到xsl:stylesheet標記,但未將名稱空間添加到匹配字段。 – dmo 2008-11-07 19:20:46

0

它的工作原理,當我從你的源文件刪除此:

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 

我不相信你的最後兩個模板都匹配。 (您可以通過將像在你的FlowDocument模板包裹<DIV>測試。)

+0

FlowDocument直接來自WPF RichTextBox,所以我寧願在xslt中處理它,而不是通過操作源代碼。添加命名空間並限定元素匹配字段修復了問題。 – dmo 2008-11-07 19:30:03

0

剛剛嘗試改變

:在您的XSL文件 「XSL模板匹配= '/'」

標籤與

「的xsl:模板匹配= '*'」

這應該給你所需的輸出。