How to create XML with XML::Twig containg a namespace declaration and prefixed names?

一笑奈何 提交于 2019-12-06 06:10:38

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.

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);

output

<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>

UPDATE

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!