如何解析“无效的”嵌套的XML标记

问题描述:

我试图构建一个XSLT文件,查找类似下面,它使用的标签无效的嵌套的XML文件:如果我想如何解析“无效的”嵌套的XML标记

<Page> 
<Content> 
    <par>This content <i>contains</i> some HTML <b><i>tags</i></b>.</par> 
    <par>This content <b>also</b> contains some HTML <i><b>tags</b></i>.</par> 
</Content> 
</Page> 

我们输出内容到一个新的文档,我有这样的事情:

<xsl:template match="Page/Content"> 
    <xsl:text disable-output-escaping="yes">&lt;![CDATA[</xsl:text> 
    <xsl:for-each select="par"> 
    <xsl:apply-templates select="."/> 
    </xsl:for-each> 
    <xsl:text disable-output-escaping="yes">]]&gt;</xsl:text> 
</xsl:template> 

<xsl:template match="par"> 
    <p><xsl:value-of select="." /></p> 
</xsl:template> 

<xsl:template match="b"> 
    <strong><xsl:value-of select="." /></strong> 
</xsl:template> 

<xsl:template match="i"> 
    <em><xsl:value-of select="." /></em> 
</xsl:template> 

我的问题是我怎么需要编辑template match="par"使得<b><i>标签正确显示?

我试过的东西

<xsl:template match="par"> 
    <p> 
    <xsl:apply-templates select="i"/> 
    <xsl:apply-templates select="b"/> 
    <xsl:value-of select="." /></p> 
</xsl:template> 

但始终会导致输出的顺序不正确,因为<i><b>标签完整的段落之前显示。 有没有可能在不改变原始XML格式的情况下做到这一点?

我没有在您的示例输入中看到任何不正确的嵌套标签,所以我不确定你的意思。 XSLT无法处理错误的嵌套XML,因为它不是有效的XML。

无论如何,你的XSLT的主要问题是,你正在使用value-of,你应该使用apply-templates

<xsl:template match="Page/Content"> 
    <xsl:text disable-output-escaping="yes">&lt;![CDATA[</xsl:text> 
    <xsl:apply-templates select="par"/> 
    <xsl:text disable-output-escaping="yes">]]&gt;</xsl:text> 
</xsl:template> 

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

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

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

但是,你还没有告诉我们你想要所以我输出不确定这会完全解决您的问题。

+0

感谢您的快速答案。这似乎解决了我的问题。的确,我错误地认为XML是无效的,这似乎是不真实的。 – Honoki 2013-05-03 10:39:04