http://www.perlmonks.org?node_id=879131

morgon has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

my application recives XML-documents that contain a declaration (I hope that is the proper term), i.e. they start with something like

<?xml version="1.0" encoding="UTF-8"?>
I now need to get to the encoding-value (not to read the XML but to generate a response with the same encoding).

I parse the XML with XML::LibXML and access the content with XPath (using XML::LibXML::XPathContext) but I cannot find a way to access the declaration.

According to "XML in a Nutshell" the declaration is not addressable via XPath anyway, so I wonder how to do that (apart from the obious regex-hack).

Many thanks!

Replies are listed 'Best First'.
Re: accessing XML-declarations
by PeterPeiGuo (Hermit) on Dec 25, 2010 at 04:00 UTC

    Access it through the actualEncoding method() of the document object:

    my $doc = $parser->parse_file("test.xml"); print $doc->actualEncoding();

    Peter (Guo) Pei

Re: accessing XML-declarations
by grantm (Parson) on Dec 26, 2010 at 04:13 UTC
    Why do you need to generate a response using the same encoding? Given that every XML parser is required to understand UTF-8 encoding why not just use that?