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

隐身守侯 提交于 2019-12-10 11:28:20

问题


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.

The output should be something like this:

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

I suppose it would look somewhat like this:

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;

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


回答1:


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


来源:https://stackoverflow.com/questions/9885732/how-to-create-xml-with-xmltwig-containg-a-namespace-declaration-and-prefixed-n

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