转换XML元素,其内容是里面CDATA转换XML元素,其内容是里面CDATA(Convert an

2019-05-12 05:28发布

我有象下面这样的XML片段

<Detail uid="6">
    <![CDATA[
    <div class="heading">welcome to my page</div>
    <div class="paragraph">this is paraph</div>
    ]]>
</Detail>

我希望能够改变

<div class="heading">...</div> to <h1>Welcome to my page</h1>
<div class="paragraph">...</div> to <p>this is paragraph</p>

你知道我该怎么做,在XSLT 1.0

Answer 1:

怎么样运行两个变换。

经过1)

<?xml version="1.0" encoding="UTF-8"?>
  <xsl:stylesheet
   version="1.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" encoding="UTF-8"/>

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

    <xsl:template match="Detail">
        <Detail>
            <xsl:copy-of select="@*"/>
        <xsl:value-of select="." disable-output-escaping="yes" />
        </Detail>
    </xsl:template>

</xsl:stylesheet>

会产生:

<?xml version="1.0" encoding="UTF-8"?>
<Detail uid="6"> 
    <div class="heading">welcome to my page</div>
    <div class="paragraph">this is paraph</div>
</Detail>

通过2)

<?xml version="1.0" encoding="UTF-8"?>
  <xsl:stylesheet
   version="1.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" encoding="UTF-8"/>

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

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*| node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="div[@class='heading']">
        <h1><xsl:value-of select="."/></h1>
    </xsl:template>

    <xsl:template match="div[@class='paragraph']">
        <p><xsl:value-of select="."/></p>
    </xsl:template>

</xsl:stylesheet>

生产:

<?xml version="1.0" encoding="UTF-8"?>
<Detail uid="6">
<h1>welcome to my page</h1>
<p>this is paraph</p>
</Detail>


Answer 2:

你不能告诉XSL 1.0鱼串出一个CDATA和解析为XML。



Answer 3:

你不能“删除”的CDATA,但你可以有点粗制滥造达到所需的输出:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
   <Detail>
        <xsl:variable name="before" select="substring-before(//Detail,'&lt;div class=&quot;heading&quot;&gt;')" />
        <xsl:variable name="afteropen" select="substring-after(//Detail,'&lt;div class=&quot;heading&quot;&gt;')" />
        <xsl:variable name="body" select="substring-before($afteropen, '&lt;/div&gt;')" />
        <xsl:variable name="after" select="substring-after($afteropen, '&lt;/div&gt;')" />
        <xsl:value-of select="concat($before, '&lt;h1&gt;', $body, '&lt;/h1&gt;',$after)"
                disable-output-escaping="yes"       />
   </Detail>
</xsl:template>
</xsl:stylesheet>

这将对于第一种类型的DIV你试图解析工作,你可以按照与第二个类似的东西。 它可以作出一些努力更通用。



文章来源: Convert an xml element whose content is inside CDATA
标签: xml xslt cdata