【问题标题】:Replace characters with entities within XML attributes用 XML 属性中的实体替换字符
【发布时间】:2016-12-27 18:01:47
【问题描述】:

我想在 XML 元素中转义双引号。比如

来自

<person name="Tiberius Claudius "Maximus"" sex="M">

<person name="Tiberius Claudius &quot;Maximus&quot;" sex="M">

我能够使用 sed 隔离属性值:

$ cat sample.xml | sed -r 's/(<person name=")(.*)(" sex.*)/\2/'
  Tiberius Claudius "Maximus"

有没有办法在第二组中用&amp;quot; 替换双引号"

【问题讨论】:

  • sed 从什么时候开始支持.*?
  • 我看到您将 Perl 作为您的标签之一,这很好,因为您需要像 XML::Twig 这样的适当 XML 解析器,而 sed 没有。您还应该使用XML::Entities 对您的文本进行编码。
  • @Borodin 曾经有。我删除了“perl”标签,因为标题或问题中的任何内容都与 perl 无关。 :-/
  • 您能否提供一个使用 XML::Entities 的示例?谢谢!
  • 我现在看到你已经删除了你的 Perl 标签。这是一个非常糟糕的举动。使用正则表达式模式可靠地解析 XML 是不可能的。

标签: regex perl replace sed


【解决方案1】:
perl -i~ -pe's{<person name="\K(.*?)(?=" sex)}{ $1 =~ s/"/&quot;/gr }eg' sample.xml

或者如果你没有 5.14,

perl -i~ -pe's{<person name="\K(.*?)(?=" sex)}{ ( my $s = $1 ) =~ s/"/&quot;/g; $s }eg' sample.xml

【讨论】:

    【解决方案2】:

    使用 perl,您可以像这样进行查找和替换:

    查找:

    (?<!=)(")(?![^"]*\s+\w+=|[^"]*\/?>)
    

    替换为:

    &quot;
    

    Live demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-29
      • 1970-01-01
      • 2016-07-10
      • 2012-06-14
      • 2023-03-11
      • 1970-01-01
      • 2010-11-13
      相关资源
      最近更新 更多