string value of every element

P

Phantom

Simple question that's driving me freakin mad.

how do I get the complete string value of, e.g.

<fruits>
<fruit>apple</fruit>
<fruit>banana</fruit>
<fruit>pear</fruit>
</fruits>

if I try string(fruits) I get only "apple"... I need "apple banana pear".

(yes, I'll actually need those spaces too)

ANY ideas before I go completely postal?

I have Googled my BRAINS out for this, and I Google for a living.

thanks guys.
P.
 
J

Joe Kesselman

Phantom said:
Simple question that's driving me freakin mad.

Hard to answer without seeing your code -- are you working with XPath,
or with the DOM, or with one of the other APIs/tools? Are you sure that
whatever being returned doesn't need to be iterated over to retrieve the
rest of the content?

In XPath, the string value of the fruits element is normally going to be
all text contained within it -- which will include the newlines:

"
apple
banana
pear
"

If you had asked for the string value of /fruits/fruit, you would get
"apple", since the string value of a multiple-node result is the string
value of the first match. You'd need to iterate through the results to
gather the other values, and of course concatenating them into a string
would be your responsibility.

If you're using the simple DOM operations, elements don't have a string
value; you must navigate the tree and gather the values. The DOM's XPath
support, if present in your DOM, has an operation which will do the
gather-and-concatenate operation -- but again, it's going to include the
newlines.
 
M

Martin Honnen

Phantom said:
Simple question that's driving me freakin mad.

how do I get the complete string value of, e.g.

<fruits>
<fruit>apple</fruit>
<fruit>banana</fruit>
<fruit>pear</fruit>
</fruits>

if I try string(fruits) I get only "apple"... I need "apple banana pear".

(yes, I'll actually need those spaces too)

Is that XPath? Then
string(/fruits)
should give you what you are looking for.
string(/fruits/fruit)
on the other hand (with XPath 1.0) would only give you "apple".

If you use the W3C DOM Level 3 then you could use the textContent
property of the 'fruits' element to get what you want.
 

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,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top