xsl:模板匹配找不到匹配项

dmo*_*dmo 10 .net xml xslt

我正在尝试使用.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>
Run Code Online (Sandbox Code Playgroud)

这个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>
Run Code Online (Sandbox Code Playgroud)

我得到这个输出:

<html>
    <body>
  a
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

而不是预期的:

<html>
   <body>
      <p>a</p>
   </body>
</html>
Run Code Online (Sandbox Code Playgroud)

这可能是命名空间的问题吗?这是我第一次尝试xsl转换,所以我很茫然.

Rob*_*ney 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>
Run Code Online (Sandbox Code Playgroud)