如何将两个XML文件中的数据合并到同一结构中? [英] How to I combine data from two XML files into the same structure?

查看:93
本文介绍了如何将两个XML文件中的数据合并到同一结构中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个XML文件,我想将数据合并为以下示例中的相同结构.实际文件更大且更复杂,因此复制和粘贴不是有效的选择.

I have two XML files that I'd like to merge the data into the same structure as the example below. The actual files are larger and more complex so copying and pasting is not an efficient option.

有什么方法可以快速完成吗?

Is there any way that this can be done quickly?

File1.xml:

File1.xml:

<part1>
<g1> abc. 
</g1></part1>
<part2>
<g2> def.
</g2></part2>

File2.xml:

File2.xml:

<part1>
<g1> 123.
</g1></part1>
<part2>
<g2> 456.
</g2></part2>

Combined.xml

Combined.xml

<part1>
<g1> abc. 123.
</g1></part1>
<part2>
<g2> def. 456.
</g2></part2>

推荐答案

是的,有很多合并" XML的方法.但是您需要做的是XML解析器,因为XML是一种结构化的数据格式.

Yes, there's loads of ways to 'merge' XML. But what you're going to need to do it is an XML parser, because XML is a structured data format.

您使用哪种语言很大程度上是您喜欢哪种语言的问题?

Which one you use is very much a question of which language do you prefer?

我吗?我喜欢Perl和XML::Twig:

Me? I like Perl and XML::Twig:

#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;
use Data::Dumper;

my $snippet1 = '<root><part1>
<g1> abc. 
</g1></part1>
<part2>
<g2> def.
</g2></part2></root>';

my $snippet2 = '<root><part1>
<g1> 123.
</g1></part1>
<part2>
<g2> 456.
</g2></part2></root>';


my $first = XML::Twig->new()->parse($snippet1);

sub merge {
    my ( $twig, $element ) = @_;
    return unless $element->tag =~ m/^g/;
    my $cur   = $element;
    my $xpath = '';
    while ( $cur->parent ) {
        $xpath = $cur->tag . "/" . $xpath;
        $cur   = $cur->parent;
    }

    # print "/",$xpath,"\n";

    if ( my $other = $first->get_xpath( $xpath, 0 ) ) {
        if (    $element->text_only
            and $other->text_only )
        {
            $element->set_text(
                ( $other->text_only . " " . $element->text_only ) =~ s/\n//rg );
        }
    }
}

my $combined = XML::Twig->new(
    pretty_print  => 'indented_a',
    twig_handlers => { '_all_' => \&merge }
)->parse($snippet2)->print;

这将获取您的源文本并将其转换为:

This'll take your source text and turn it into:

<root>
  <part1>
    <g1> abc.   123.</g1>
  </part1>
  <part2>
    <g2> def.  456.</g2>
  </part2>
</root>

但是我敢肯定,您可以选择更好的路线,以及可以使用的其他语言.

But I'm sure there's better routes you can take, and other languages you can use.

这篇关于如何将两个XML文件中的数据合并到同一结构中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆