I recently had a need to create an XML document to send to a web
service, and decided to try and use the DOM API of XML::LibXML to do it.
I needed to create a document with a namespace that would look something
like:
<?xml version="1.0" encoding="UTF-8"?>
<tns:Request tns:version="1"
xmlns:tns="http://www.example.com/services/delivery">
<tns:Id>1138800</tns:Id>
</tns:Request>
I figured there would be some DOM method where I could declare the
namespace URI and prefix for the document, or perhaps the root node, and
then it would get automatically applied to all subsequent child nodes.
Instead, I ended up having to do:
my $doc = XML::LibXML::Document->new('1.0', 'UTF-8');
# setup name space
my $nsURI = 'http://www.example.com/services/delivery';
my $pfx = 'tns';
# add nodes
my $root = $doc->createElementNS($nsURI, "$pfx:Request");
$root->setAttributeNS($nsURI, "$pfx:version", '1');
$doc->setDocumentElement($root);
my $id = $root->addNewChild($nsURI, "$pfx:Id");
$id->appendText($self->Id);
...
where I essentially manually set the prefix, and had to pass in the
namespace URI to every node creation call. (XML::LibXML docs implied it
was normal to pass a prefix as part of a node name.)
The addNewChild() method of XML::LibXML::Node, per the documentation,
isn't part of the DOM standard. It also doesn't seem to do anything
meaningful with the $nsURI parameter. Even without a prefix supplied, it
doesn't add an 'xmlns' attribute with the URI, as I would expect, and as
createElementNS() does.
I believe I could have also replaced:
my $id = $root->addNewChild($nsURI, "$pfx:Id");
with:
my $id = XML::LibXML::Element->new("Id");
$id->setNamespace($nsURI , $pfx);
$root->addChild($id);
which seems more correct, but isn't much of a win from a conciseness
perspective, though it could be consolidated into a helper method.
Am I missing something in the DOM API, or is it really this cumbersome
to deal with namespaces?
-Tom
--
Tom Metro
Venture Logic, Newton, MA, USA
"Enterprise solutions through open source."
Professional Profile: http://tmetro.venturelogic.com/
_______________________________________________
Boston-pm mailing list
[email protected]
http://mail.pm.org/mailman/listinfo/boston-pm