如何阅读和更改<!Doctype>标签和<?xml version ="1.0"?>在xml树枝中? [英] how to read and change <!Doctype> tag and <?xml version="1.0"?> in xml twig?

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

问题描述

我是xml twig的新手...如何读取和更改<!DOCTYPE article SYSTEM "loose.dtd"><?xml version="1.0" encoding="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 ?> and <!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;标签和&lt;?xml version ="1.0"?&gt;在xml树枝中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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