Is there any method to gain the text like this?

11 views
Skip to first unread message

Meiyan Wang

unread,
Dec 5, 2010, 10:37:58 PM12/5/10
to support-querypath
Hi, everyone, I have a problem:

a xml doc like this,

<root>
<c1> 11</c1>
<c2> 222<c3>333</c3></c2>
</root>

how can I get the 222? I use text(), but it will return 222333. I have
carefully read the doc and source of querypath, but there isn't a
proper method.

Thanks a lot.

TechnoSophos

unread,
Dec 6, 2010, 11:52:16 AM12/6/10
to support-...@googlegroups.com
This is a great question, and one that's bothered me for a while. It
seems like there ought to be a straightforward way of doing this with
the existing API, but it's actually more complicated than it sounds.
Perhaps I should add a new method for just this sort of thing.

Anyway, here are two ways of doing this. I happen to think that the
first way is really ugly... but it works:

$test = '<?xml version="1.0"?>


<root>
<c1> 11</c1>
<c2> 222<c3>333</c3></c2>

</root>';

// Get rid of competing children
$qp = qp($test, 'c2');
$qp->branch()->children('c3')->remove();
print $qp->text();

// Get just the first DOMNode and fetch its text. We
// use contents() because it returns text nodes as
// well as elements.
print qp($test, 'c2')->contents()->get(0)->textContent;

This second example can be altered to get *all text in the immediate
element*, but none from the child elements:

$nodes = qp($test, 'c2')->contents()->get();

foreach ($nodes as $node) {
if ($node->nodeType == XML_TEXT_NODE) {
print $node->textContent;
}
}

Again, not pretty... but that's how to do it.

Matt

> --
> You received this message because you are subscribed to the Google Groups "support-querypath" group.
> To post to this group, send email to support-...@googlegroups.com.
> To unsubscribe from this group, send email to support-queryp...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/support-querypath?hl=en.
>
>

--
http://technosophos.com
http://querypath.org

Meiyan Wang

unread,
Dec 9, 2010, 2:27:33 AM12/9/10
to support-querypath
Thanks a lot! :)

It's really useful.
Reply all
Reply to author
Forward
0 new messages