0

I'm having difficulty writing to a strings.xml file that contains an XLIFF element using LibXML. Note that I'm trying to write a value that already exists (had no problem parsing the node while reading). I also need to use appendWellBalancedChunk as I write HTML elements sometimes.

#!/usr/bin/env perl

#
# Create a simple XML document
#

use strict;
use warnings;
use XML::LibXML;

my $doc = XML::LibXML::Document->new('1.0', 'utf-8');
my $root = $doc->createElement("resources");
$root->setAttribute('xmlns:xliff' => 'urn:oasis:names:tc:xliff:document:1.2');
my $tag = $doc->createElement("string");
$tag->setAttribute('name'=>'no_messages');
my $string = '<xliff:g id="MILLISECONDS">%s</xliff:g>ms';
$tag->appendWellBalancedChunk($string);
$root->appendChild($tag);

$doc->setDocumentElement($root);
print $doc->toString();

When I run this, I get the following:

$ perl xliff.pl
namespace error : Namespace prefix xliff on g is not defined
<xliff:g id="MILLISECONDS">%s</xliff:g>ms
                          ^

Thanks

cdm
  • 719
  • 2
  • 10
  • 22

2 Answers2

1

Adding a namespace declaration to the xml element will make your code run without errors:

my $string = '<xliff:g xmlns:xliff="urn:whatever" id="MILLISECONDS">%s</xliff:g>ms';
collapsar
  • 17,010
  • 4
  • 35
  • 61
  • That worked. Is it possible to add that to the resource tag to avoid adding this to every element that has an XLIFF element? Was hoping something like this would work, but no luck... #!/usr/bin/env perl # # Create a simple XML document # use strict; use warnings; use XML::LibXML; my $doc = XML::LibXML::Document->new('1.0', 'utf-8'); my $root = $doc->createElement("resources"); $root->setAttribute('xmlns:xliff' => 'urn:oasis:names:tc:xliff:document:1.2'); ... – cdm Feb 13 '15 at 12:16
  • you can add the namespace declaration to any element. Its scope is the subtree rooted in this element. So, yes, that's possible. – collapsar Feb 13 '15 at 12:20
  • Doesn't seem to work for me. I've updated the code in the original question so you can see exactly what I'm doing. Thanks for your help! – cdm Feb 13 '15 at 12:31
  • Yeah, seems that i've remembered wrongly. This appears to be a problem with the parsing of 'appendWellBalancedChunk', apparently the parser would need some hints about namepaces used. imho libxml can be picky when it comes to namespaces ... – collapsar Feb 13 '15 at 12:39
  • Thanks, at least I know I'm not doing something wrong. – cdm Feb 13 '15 at 13:07
0

You are getting this error because you don't have an XML namespace defined for <xliff:g id="MILLISECONDS">%s</xliff:g>ms

serenesat
  • 4,611
  • 10
  • 37
  • 53