【问题标题】:Replace < in XML/HTML with " (RegEx)将 XML/HTML 中的 < 替换为 " (RegEx)
【发布时间】:2013-01-23 09:51:46
【问题描述】:
我有一个 XML/HTML (epub) 文档,内容中有 < > 而不是 " " 用于引用。是否有可能只替换 < > 的内容,而用一些正则表达式保持 <tags> 不变?
【问题讨论】:
标签:
html
xml
regex
replace
epub
【解决方案1】:
You should not use Regex to parse XML
您的问题并不完全清楚,但听起来您的 XML 中有一些带有 < 和 > 的文本值,您想将其更改为引号。这可以通过 XSLT 轻松完成:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@* | *">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="translate(., '<>', '""')"/>
</xsl:template>
</xsl:stylesheet>
在此输入上运行时:
<root>
<item>And he said <hello!>.</item>
<item><hello!>, he said</item>
<section>
<content><What's up></content>
</section>
</root>
它产生:
<root>
<item>And he said "hello!".</item>
<item>"hello!", he said</item>
<section>
<content>"What's up"</content>
</section>
</root>
您的文档中的文本可能包含您不想转换为引号的<s 和>s 是否存在风险?