0

I have done a lot of searches on google, but is there a way to parse and get values similar to extracting values from a file, if the XML is contained in the string.

Following is a sample script:

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

my $xml  = "<family><id>25502</id><father><id>1</id></father><mother><id>2</id></mother><son><id>2</id></son></family>";

my $id = $xml->getElementsByTagName("id")->item(0)->getFirstChild->getData;

print $id;

In this example, I could not print the ID. Please help. Thanks.

1
  • And you didn't think it was worthwhile to mention that you're receiving an error message when you try this? Can't call method "getElementsByTagName" without a package or object reference Commented Nov 6, 2017 at 22:05

2 Answers 2

8

You seem to misunderstand how objects and XML parsing work. You can't just use a module and suddenly expect it to have an effect on all variables in your program.

If you read the documentation for XML::LibXML::Parser it will show you how to parse your XML string into a document object which you can then query using various methods.

You will want code like this:

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

my $xml = '<family> ... </family>';

my $xml_parser = XML::LibXML->new;

my $doc = $xml_parser->parse_string($xml);

You now have a XML document variable (in $doc) that you can call the XML::LibXML methods on.

Sign up to request clarification or add additional context in comments.

Comments

3

You code will work with the fix describe by Dave Cross, but it can be made much more concise

I recommend something like this. Note that, when called in list context, getChildrenByTagName returns a list of XML::LibXML::Node objects instead of one XML::LibXML::NodeList object. The same applies to any method that returns a list of nodes.

use strict;
use warnings;
use feature 'say';

use XML::LibXML;

my $xml = <<__END_XML__;
<family>
    <id>25502</id> 
    <father>
        <id>1</id>
    </father>
    <mother>
        <id>2</id>
    </mother>
    <son>
        <id>2</id>
    </son>
</family>
__END_XML__

my $doc = XML::LibXML->load_xml( string => $xml );

my ($family_id) = $doc->documentElement->getChildrenByTagName('id');

say $family_id->textContent;

output

25502

And if you are expecting to do much work with XML then you should familiarise yourself with XPath. With its help the above assignment could be written as

my ($family_id) = $doc->findnodes('/family/id');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.