2013-11-28 75 views
0

我是新來的xml樹枝...如何閱讀和更改<!DOCTYPE article SYSTEM "loose.dtd"><?xml version="1.0" encoding="UTF-8"?>。我怎麼能在這個TAG更改..因爲我不知道如何將這種讀取和XML ::嫩枝更改此標記...如何在xml樹枝中讀取並更改<!Doctype>標記和<?xml version =「1.0」?>?

我輸入:

<?xml version="1.0" encoding="UTF-8"?> 

<!DOCTYPE art SYSTEM "loose.dtd"> 
<art> 
<fr> 
<p>Text</p> 
<p>Text</p> 
</fr> 
<fr> 
<p>Text</p> 
<p>Text</p> 
</fr> 
</art> 

我需要的輸出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<DTD> 
<Contents type="&lt;!DOCTYPE article SYSTEM &quot;loose.dtd&gt;"/> 
</DTD> 
<art> 
<fr> 
<p>Text</p> 
<p>Text</p> 
</fr> 
<fr> 
<p>Text</p> 
<p>Text</p> 
</fr> 
</art> 

如何可以改變<?xml ?> and <!Doctype>標籤,可你的任何一個幫助這個過程..

+1

您的xml輸出格式不正確。它有兩個根元素,只有一個是可能的。 – Birei

回答

1

你可以試試以下(代碼它的註釋)。最重要的一點理解它是創建一個新的twig,複製要保持和創造什麼它改變了所有的元素:

#!/usr/bin/env perl 

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

## Create a twig based in an input xml file. 
my $twig = XML::Twig->new; 
$twig->parsefile(shift); 

## Create a new twig that will be the output. 
my $new_twig = XML::Twig->new(pretty_print => 'indented'); 

## Create a root tag. 
$new_twig->set_root(XML::Twig::Elt->new('root')); 

## Create the xml processing instruction. 
my $e = XML::Twig::Elt->new('k' => 'v'); 
$e->set_pi('xml', 'version="1.0" encoding="UTF-8" standalone="yes"'); 
$e->move(before => $new_twig->root); 

## Copy the whole tree from the old twig. 
my $r = $twig->root; 
$r->paste(first_child => $new_twig->root); 

## Copy the doctype from the old twig to the new one. 
my $contents_elt = XML::Twig::Elt->new(Contents => { type => $twig->doctype }); 
my $dtd_elt = XML::Twig::Elt->new(DTD => '#EMPTY'); 
$contents_elt->move(last_child => $dtd_elt); 
$dtd_elt->move(first_child => $new_twig->root); 

## Print the whole twig created. 
$new_twig->print; 

運行它想:

perl script.pl xmlfile 

國債收益率:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><root> 
    <DTD> 
    <Contents type="&lt;!DOCTYPE art SYSTEM &quot;loose.dtd&quot;>&#x0a;"/> 
    </DTD> 
    <art> 
    <fr> 
     <p>Text</p> 
     <p>Text</p> 
    </fr> 
    <fr> 
     <p>Text</p> 
     <p>Text</p> 
    </fr> 
    </art> 
</root> 
+0

很好的答案@Birei – AlexPandiyan

0

在發現試圖做類似的事情時,這個問題: Assembling XML in Perl

你可能希望set_pi做XML頭,而是:

$twig->set_xml_version("1.0"); 
$twig->set_encoding('utf-8'); 
$twig->set_standalone('yes'); 

XML::Twig文檔提到DTD處理,但:

DTD處理 的DTD處理方法相當竊聽。沒有人使用它們,看起來很難讓它們在所有情況下工作,包括幾個稍微不兼容的XML :: Parser和libexpat版本。

基本上你可以讀取DTD,正確地輸出它,然後更新實體,但不會更多。

因此,將XML :: Twig與獨立文檔或引用外部DTD的文檔一起使用,但不要期望它能正確分析甚至輸出回DTD。

考慮到這一點,您從Birei獲得的解決方案可能是處理它的最佳方法。

相關問題