Dot-Net

xsl:template match 找不到匹配項

  • June 8, 2010

我正在嘗試使用 .NET XslCompiledTransform 將一些 Xaml 轉換為 HTML,並且在讓 xslt 匹配 Xaml 標記時遇到了困難。例如,使用此 Xaml 輸入:

<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 轉換,所以我很茫然。

是的,這是命名空間的問題。輸入文件中的所有元素都在命名空間中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>

引用自:https://stackoverflow.com/questions/273199