Strange structure to be parsed

F

francescomoi

Hi.

I want to parse this XML file:
-----------------
<doc>
<item>
<name>John Morrow</name>
<contact type="email">[email protected]</contact>
Blah blah
</item>
</doc>
--------------------

I'm able to get 'John Morrow':
$doc->getDocumentElement()->getElementsByTagName('item')->
getElementsByTagName('name')->item(0)->getFirstChild->getNodeValue;

But I don't know to get 'Blah Blah'. Any suggestion?

Thank you very much.
 
B

Bjoern Hoehrmann

* (e-mail address removed) wrote in comp.text.xml:
I want to parse this XML file:
-----------------
<doc>
<item>
<name>John Morrow</name>
<contact type="email">[email protected]</contact>
Blah blah
</item>
</doc>
--------------------

I'm able to get 'John Morrow':
$doc->getDocumentElement()->getElementsByTagName('item')->
getElementsByTagName('name')->item(0)->getFirstChild->getNodeValue;

But I don't know to get 'Blah Blah'. Any suggestion?

Well, it's the getLastChild of the item element, so something like

$doc
->getDocumentElement()
->getElementsByTagName('item')
->item(0)
->getLastChild
->getNodeValue;

should do, depending on whether your implementation supports such a
method. You did not say what you are using so I have to guess... Note
that e.g. XPath might be a better way to query for such information.
 
G

gimme_this_gimme_that

There are so many tools to do that ... if I gave you a solution you
probably wouldn't be interested in it.
 
P

Paul Allen

Bjoern said:
* (e-mail address removed) wrote in comp.text.xml:



Well, it's the getLastChild of the item element, so something like

$doc
->getDocumentElement()
->getElementsByTagName('item')
->item(0)
->getLastChild
->getNodeValue;

should do, depending on whether your implementation supports such a
method. You did not say what you are using so I have to guess... Note
that e.g. XPath might be a better way to query for such information.

This does it, although I'd welcome critiques of the XPath expression:

--------------------- snip -------------------------
use XML::LibXML;


$parser = XML::LibXML->new();
$doc = $parser->parse_file("junkfile.xml");
$root = $doc->documentElement();
($node) = $root->findnodes("//item/child::node()[position()=last()]");
print "\"", $node->nodeValue, "\"\n";
--------------------- snip --------------------------

It prints:
"
Blah blah
"

Paul Allen
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,999
Messages
2,570,244
Members
46,838
Latest member
KandiceChi

Latest Threads

Top