如何更改名称空间 [英] How to change namespace

查看:65
本文介绍了如何更改名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用perl将名称空间和uri更改为新名称空间?文件很大(20 MB),只包含一行,并且结构很复杂. 示例:

How to change namespace and uri to new one with perl? Files are big (20 MB) and containing one line and the structures are complicated. Example:

<?xml version="1.0" encoding="utf-8"?>
<m:sr xmlns:m="http://www.example.com/mmm" xml:lang="et">
<m:A m:AS="EX" m:KF="sss1">
<m:m m:u="uus" m:O="ggg">ggg</m:m>
</m:A>

</m:sr>

收件人:

<?xml version="1.0" encoding="utf-8"?>
<a:sr xmlns:a="http://www.example.com/aaa" xml:lang="et">
<a:A a:AS="EX" a:KF="sss1">
<a:m a:u="uus" a:O="ggg">ggg</a:m>
</a:A>

</a:sr>

推荐答案

您可以使用XML :: Twig.

You can do this with XML::Twig.

下面的代码很干净,因为它对输入的假设很少,特别是它依赖于输入中名称空间的URI,而不是前缀.每当完成任何元素解析时,都会刷新树枝,因此它在内存中的存储量很少.

The code below is quite clean in that it makes very few assumptions about the input, notably it relies on the URI of the namespace in the input, not on the prefix. The twig is flushed every time any element is done parsing, so it keeps very little in memory.

#!/usr/bin/perl

use strict;
use warnings;
use XML::Twig;

# parameters, may be changed
my $SR     = 'sr';                          # local name of the root of the fragment
my $OUT    = 'a';                           # prefix in the output
my $IN_NS  = 'http://www.example.com/mmm';  # namespace URIs
my $OUT_NS = 'http://www.example.com/aaa';

my $t= XML::Twig->new( 
          map_xmlns => { $IN_NS => $OUT, $OUT_NS => $OUT, },
          start_tag_handlers => { "$OUT:$SR"  => \&change_ns_decl, },
          twig_handlers => { _all_ => sub { $_->flush; }, },
          keep_spaces => 1,
                       )
                  ->parse( \*DATA); # replace by parsefile( "my.xml");

exit;

sub change_ns_decl
  { my( $t, $sr)= @_;
    $sr->set_att( "xmlns:$OUT" => $OUT_NS);
  }

__DATA__
<?xml version="1.0" encoding="utf-8"?>
<m:sr  xml:lang="et" xmlns:m="http://www.example.com/mmm">
<m:A m:AS="EX" m:KF="sss1">
<m:m m:u="uus" m:O="ggg">ggg</m:m>
</m:A>
</m:sr>

这篇关于如何更改名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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