如何使用XML :: Twig创建XML,其中包含名称空间声明和前缀名称? [英] How to create XML with XML::Twig containg a namespace declaration and prefixed names?

查看:100
本文介绍了如何使用XML :: Twig创建XML,其中包含名称空间声明和前缀名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 XML :: Twig 从头开始创建新的XML文档.根元素应具有前缀和名称空间声明.所有子代也应属于此命名空间,并使用此前缀.

I am creating a new XML document from scratch using XML::Twig. The root element should have a prefix and a namespace declaration. All children should also belong to this namespace and use this prefix.

输出应该是这样的:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<abc:root xmlns:abc="http://www.somehost.com/abc-data/ns/5.0.0" version="5.0.0.0">
 <abc:element name="myElement">
  This is my element
 </abc:element> 
</abc:root>

我想它看起来像这样:

my $new_twig = XML::Twig->new(map_xmlns => {'http://www.somehost.com/abc-data/ns/5.0.0' => "abc"}, pretty_print => 'indented');

my $root = XML::Twig::Elt->new('root');
$new_twig->set_encoding('UTF-8');
$new_twig->set_standalone("no");
$new_twig->set_root( $root);

my $element = XML::Twig::Elt->new('element' => {'name'=>'myElement};
$element->set_text('This is my element');
$element->paste(last_child=>$root);

# print in a file
open (TMP, "> $new_file_name");   
select TMP;
$new_twig->print(\*TMP);
close TMP;

这似乎很简单,但是我还是Perl的新手,这让我很难受! 谢谢您的帮助!

This may seem simple, but I'm still a newby to Perl and this is giving me a hard time! Thanks for your help!!!

推荐答案

XML::Twig模块更多地用于处理现有XML,而不是从头开始构建新数据.创建新XML文档所需要的只是XML::Twig::Elt类:主要的XML::Twig类是不相关的.

The XML::Twig module is more for processing existing XML rather than building new data from scratch. All you need to create a new XML document is the XML::Twig::Elt class: the main XML::Twig class is irrelevant.

有许多构建XML文档的方法.这是一个示例,用于创建您作为示例显示的XML

There are many ways of building an XML document. Here is an example that creates the XML you have shown as an example

use strict;
use warnings;

use XML::Twig;

my $new_file_name = 'new.xml';

my $root = XML::Twig::Elt->new('abc:root', {
  'xmlns:abc' => "http://www.somehost.com/abc-data/ns/5.0.0",
  version => "5.0.0.0",
});
$root->insert_new_elt('abc:element' => {name => 'myElement'}, 'This is my element');
$root->set_pretty_print('indented');
$root->print_to_file($new_file_name);

输出

<abc:root version="5.0.0.0" xmlns:abc="http://www.somehost.com/abc-data/ns/5.0.0">
  <abc:element name="myElement">This is my element</abc:element>
</abc:root>


更新

如果很难升级到最新版本的XML::Twig,则可以通过将对print_to_file的调用替换为

If it is difficult to upgrade to the latest version of XML::Twig, you can achieve the equivalent effect by replacing the call to print_to_file with

open my $out, '>:utf8', $new_file_name or die qq(Cannot create "$filename": $!);
$root->print($out);

这篇关于如何使用XML :: Twig创建XML,其中包含名称空间声明和前缀名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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