[jdom-interest] Convert XML to String (get the contents of the elements) and OUTPUT Text

Frédéric Laurent fl at opikanoba.org
Tue Jan 27 00:21:16 PST 2004


>
> I am doing a project called " Annotation tool in Java " and I would like
> to
> ask you if in some way i can convert (with JDOM using Xpath or any other
> method) this xml document ....
>
> <?xml version='1.0' encoding='ISO-8859-1'?>
> <words>
> 	<word id="word_1">Annotation</word>
> 	<word id="word_2">tool</word>
> 	<word id="word_3">in</word>
> 	<word id="word_4">Java</word>
> 	<word id="word_5">.</word>
> </words>
>
> to a text document that will look like this:
>
> Annotation tool in Java.


Hello
With an xpath expression, you can select all text nodes. There are
put into a java.util.List object. Then you can easily iterate on
each text node and append it into a StringBuffer...
Sample code in Jython

----------------------------------------
from java.io import *
from java.lang import *
from org.jdom.input import *
from org.jdom.xpath import *

xmlbuffer ="""<?xml version='1.0' encoding='ISO-8859-1'?>
<words>
        <word id="word_1">Annotation</word>
        <word id="word_2">tool</word>
        <word id="word_3">in</word>
        <word id="word_4">Java</word>
        <word id="word_5">.</word>
</words>
"""

#build document

docBuilder = SAXBuilder()
doc = SAXBuilder().build(StringReader(xmlbuffer))
Result = StringBuffer()

# make xpath expression
xp = XPath.newInstance("/words/word/text()")

# iterate on nodes
for node in xp.selectNodes(doc):
	Result.append(node.getText()).append(" ")

#print result
print Result.toString()
----------------------------------------

which prints

Annotation tool in Java .


HTH

regards

-- 
XPath free testing software :  http://lantern.sourceforge.net
Frédéric Laurent                     http://www.opikanoba.org





More information about the jdom-interest mailing list