本文介绍了如何阅读和更改&lt;!Doctype&gt;标签和 <?xml 版本=“1.0"?&gt;在 xml 树枝中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 xml twig 的新手...如何阅读和更改 <?xml version="1.0" 编码="UTF-8"?> .我怎样才能修改这个标签..因为我不知道如何在 xml::Twig 中读取和更改这个标签...

I'm new to xml twig... how to read and change <!DOCTYPE article SYSTEM "loose.dtd"> and <?xml version="1.0" encoding="UTF-8"?> . how can I modification in this tag.. because i don't know how to this read and change this tag in xml::Twig...

我的意见:

<?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 ?>和 <!Doctype> 标记,你能帮助这个过程吗..

how can alter <?xml ?> and <!Doctype> tag, can you any one help this process..

推荐答案

您可以尝试以下(代码已注释).理解它的重点是创建一个新的twig,复制你想要保留的所有元素并创建它更改的内容:

You can try the following (code it's commented). The important point to understand it is to create a new twig, copy all the elements you want to keep and create what it changes:

#!/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>

这篇关于如何阅读和更改&lt;!Doctype&gt;标签和 <?xml 版本=“1.0"?&gt;在 xml 树枝中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 00:33