【问题标题】:Unable to figure out how to replace a tag in xml无法弄清楚如何替换 xml 中的标签
【发布时间】:2019-08-21 22:40:57
【问题描述】:

需要帮助找出正确的正则表达式以将 xml 标记替换为文件的内容。

尝试了一些基本的东西,比如转义特殊字符,但没有运气。愿意使用 sed 以外的其他东西。

config.txt

    <localReplications/>

用config.txt替换

    <localReplications>
        <localReplication>
            <enabled>true</enabled>
            <cronExp>0 0 /5 * * ?</cronExp>
            <syncDeletes>true</syncDeletes>
            <syncProperties>true</syncProperties>
            <repoKey>some-repo-key</repoKey>
            <url>https://foo.bar/random</url>
            <socketTimeoutMillis>15000</socketTimeoutMillis>
            <username>foo</username>
            <password>bar</password>
            <enableEventReplication>true</enableEventReplication>
            <syncStatistics>false</syncStatistics>
        </localReplication>
    </localReplications>

&lt;localReplications/&gt; 标签是非常复杂的 xml 文件的一部分。我希望 &lt;localReplications/&gt; 被替换为 replace-with-config.txt 中的内容

【问题讨论】:

  • 不要使用正则表达式来解析和/或修改 XML。使用真正的 XML 解析器,在您的情况下,XSLT 处理器将能够完全满足您的需求。 Perl 具有 XSLT 绑定,如多个地方所述,包括 here
  • 我建议使用 XML/HTML 解析器(例如 xmlstarlet)。

标签: regex bash perl sed


【解决方案1】:
use XML::LibXML qw();
my $config = XML::LibXML
    ->load_xml(location => 'config.txt');
my $replace = (XML::LibXML
    ->load_xml(location => 'replace-with-config.txt')
    ->findnodes('//localReplications')
)[0];
for my $local_replications (
    $config->findnodes('//localReplications')
) {
    # $local_replications->replaceNode($replace);
    # this fails with HIERARCHY_REQUEST_ERR,
    # so do it in two steps instead
    $local_replications->addSibling($replace);
    $local_replications->unbindNode;
}
print $config->toString;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 2013-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多