對我來說最合適的工作是在傳入文檔上使用XSLT對這些文件進行雙重轉義(並在傳出文檔中對此進行反轉)。
因此<
中的屬性變爲&lt;
。感謝@Abel的建議。
這裏是我加的是XSLT,以防其他人發現它的幫助:
首先是在XSLT 1.0做字符串替換模板。如果您可以使用XSLT 2.0,則可以使用內置的replace
。
<xsl:template name="string-replace-all">
<xsl:param name="text"/>
<xsl:param name="replace"/>
<xsl:param name="by"/>
<xsl:choose>
<xsl:when test="contains($text, $replace)">
<xsl:value-of select="substring-before($text,$replace)"/>
<xsl:value-of select="$by"/>
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="substring-after($text,$replace)"/>
<xsl:with-param name="replace" select="$replace"/>
<xsl:with-param name="by" select="$by"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
下一步是做我需要的特定更換模板:
<!-- xml -> html -->
<xsl:template name="replace-html-codes">
<xsl:param name="text"/>
<xsl:variable name="lt">
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="$text"/>
<xsl:with-param name="replace" select="'<'"/>
<xsl:with-param name="by" select="'&lt;'"/>
</xsl:call-template>
</xsl:variable>
<xsl:variable name="gt">
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="$lt"/>
<xsl:with-param name="replace" select="'>'"/>
<xsl:with-param name="by" select="'&gt;'"/>
</xsl:call-template>
</xsl:variable>
<xsl:value-of select="$gt"/>
</xsl:template>
<!-- html -> xml -->
<xsl:template name="restore-html-codes">
<xsl:param name="text"/>
<xsl:variable name="lt">
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="$text"/>
<xsl:with-param name="replace" select="'&lt;'"/>
<xsl:with-param name="by" select="'<'"/>
</xsl:call-template>
</xsl:variable>
<xsl:variable name="gt">
<xsl:call-template name="string-replace-all">
<xsl:with-param name="text" select="$lt"/>
<xsl:with-param name="replace" select="'&gt;'"/>
<xsl:with-param name="by" select="'>'"/>
</xsl:call-template>
</xsl:variable>
<xsl:value-of select="$gt"/>
</xsl:template>
的XSLT主要是直通。我只是調用相應的模板時複製屬性:
<xsl:template match="@*">
<xsl:attribute name="data-{local-name()}">
<xsl:call-template name="replace-html-codes">
<xsl:with-param name="text" select="."/>
</xsl:call-template>
</xsl:attribute>
</xsl:template>
<!-- copy all nodes -->
<xsl:template match="node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
@Abel我使用jQuery的'的.html()',我只是試圖轉降低到我認爲的「問題」發生。源文檔是XML,在用'.html()'插入之前,我通過瀏覽器XSLT運行。稍後,我通過逆向過程來取回XML。我只是覺得很奇怪,DOM是* unescaping *這個角色(而不是其他人)。 – murrayju
我無法修改源XML,並且需要在最後的輸出中保留相同的內容。我可以在中間運行任何需要的轉換,但是我正在尋找一種比一些正則表達式更好的方法。特別是考慮到文件充滿的'<'。 – murrayju
@Abel我唯一的目標是以與它相同的方式將其從DOM中取出(如'<')。我用'.text(string)'把它放入''.text()'出來。我這次往返的問題是輸入不等於輸出(僅在這種情況下)。 – murrayju