【问题标题】:Replace < in XML/HTML with " (RegEx)将 XML/HTML 中的 < 替换为 " (RegEx)
【发布时间】:2013-01-23 09:51:46
【问题描述】:

我有一个 XML/HTML (epub) 文档,内容中有 &lt; &gt; 而不是 " " 用于引用。是否有可能只替换 &lt; &gt; 的内容,而用一些正则表达式保持 &lt;tags&gt; 不变?

【问题讨论】:

  • 你能举个例子吗?
  • 只是为了确定,他们看起来像«吗?
  • 这个问题不清楚。请举例说明。

标签: html xml regex replace epub


【解决方案1】:

You should not use Regex to parse XML

您的问题并不完全清楚,但听起来您的 XML 中有一些带有 &lt;&gt; 的文本值,您想将其更改为引号。这可以通过 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(., '&lt;&gt;', '&quot;&quot;')"/>
  </xsl:template>
</xsl:stylesheet>

在此输入上运行时:

<root>
  <item>And he said &lt;hello!&gt;.</item>
  <item>&lt;hello!&gt;, he said</item>
  <section>
    <content>&lt;What's up&gt;</content>
  </section>
</root>

它产生:

<root>
  <item>And he said "hello!".</item>
  <item>"hello!", he said</item>
  <section>
    <content>"What's up"</content>
  </section>
</root>

您的文档中的文本可能包含您不想转换为引号的&lt;s 和&gt;s 是否存在风险?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-07
    • 2013-05-04
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多