2013-11-05 35 views
1

我是Perl新手。我想將xml根標記和根結束標記讀取到perl變量。如何將根標記和根關閉標記讀取到Perl變量?

我試過這個正常的文件閱讀。有效。我得到了第一條線和最後一條線。但是如果沒有新線,有些時候你不能相信第一條線。所以用正則表達式來閱讀第一行。

但我GOOGLE了它的一些內置Perl xml函數來完成這件事。我沒有找到任何東西,即對我來說都是新的。

請讓我知道哪個庫最適合這個。如果可能,舉一些例子

如: -

<nst:root arg='1' arg2='2' arg3='3'> 
    <a>1</a> 
    <b>2</b> 
</nst:root> 

我想2變量一樣,

$root = '<nst:root arg='1' arg2='2' arg3='3'>'; 
$rootClose = '</nst:root>'; 

我想,以取代其他XML這根標籤。請幫忙。

這就是我想要做的。我有一個XML文件,並有實際的根標籤。我使用XML::Twig::xml_split將該文件分成多個文件。我收到很多文件,但標題不同。我想從主文件更新與實際標題中的子文件

EG: -

拆分限制爲2

實際文件,

<nst:root arg='1' arg2='2' arg3='3'> 
     <a>1</a> 
     <a>1</a> 
     <a>1</a> 
     <a>1</a> 
     <a>1</a> 
     <a>1</a> 
</nst:root> 

它將拆分,3檔與XML::Twig::xml_split。插件添加自己的標題。

File1:- 
<xml_split:root xmlns:xml_split="http://xmltwig.com/xml_split"> 
      <a>1</a> 
      <a>1</a> 
</xml_split:root> 

File2:- 
<xml_split:root xmlns:xml_split="http://xmltwig.com/xml_split"> 
      <a>1</a> 
      <a>1</a> 
</xml_split:root> 

File3:- 
<xml_split:root xmlns:xml_split="http://xmltwig.com/xml_split"> 
      <a>1</a> 
      <a>1</a> 
</xml_split:root> 

我希望它像

File1:- 
<nst:root arg='1' arg2='2' arg3='3'> 
      <a>1</a> 
      <a>1</a> 
</nst:root> 

File2:- 
<nst:root arg='1' arg2='2' arg3='3'> 
      <a>1</a> 
      <a>1</a> 
</nst:root> 

File3:- 
<nst:root arg='1' arg2='2' arg3='3'> 
      <a>1</a> 
      <a>1</a> 
</nst:root> 
+0

@mirod你能幫助我在這? – Sahal

+0

爲什麼你想在一個變量中打開標籤,在另一個變量中關閉另一個變量?聲明該名稱空間在哪裏? – Birei

+0

看到這就是我想要做的。我有一個XML文件,並有實際的根標籤。我使用'XML :: Twig :: xml_split'將該文件分割成多個文件。我收到很多文件,但標題不同。我想用主文件中的實際標題來更新子文件。 – Sahal

回答

1

我不知道如何使用xml_split程序,但在這裏,你必須使用XML::Twig模塊,我在那裏創建新的元素和移動每對孩子的的方法從一棵樹到另一:

#!/usr/bin/env perl 

use strict; 
use warnings; 
use XML::Twig; 
use POSIX qw<ceil>; 

my ($split_limit, $n) = (2, 0); 

my $twig = XML::Twig->new->parsefile(shift); 
my $root = $twig->root; 

for ( 1 .. ceil($root->children_count/$split_limit)) { 
    my $t = XML::Twig::Elt->new($root->tag, $root->atts); 
    for (1 .. $split_limit) { 
     my $children = $root->first_child; 
     last unless $children; 
     $children->move(last_child => $t); 
    } 
    $t->print_to_file('xmlfile-' . $n++ . '.xml'); 
} 

運行它想:

perl script.pl xmlfile 

這產生了一個文件,每對與它的頭根部的孩子的的:

==> xmlfile-0.xml <== 
<nst:root arg="1" arg2="2" arg3="3"><a>1</a><a>1</a></nst:root> 
==> xmlfile-1.xml <== 
<nst:root arg="1" arg2="2" arg3="3"><a>1</a><a>1</a></nst:root> 
==> xmlfile-2.xml <== 
<nst:root arg="1" arg2="2" arg3="3"><a>1</a><a>1</a></nst:root> 
+0

我試過了,它沒有改變任何父標籤。 – Sahal

+0

我想要孩子的XML文件頭應替換原始文件。不是子元素標題 – Sahal

+0

@Sahal:我不明白你。根據您的輸入提供樣本輸出數據。 – Birei