RosettaCodeData/Task/XML-XPath/NetRexx/xml-xpath.netrexx

80 lines
2.4 KiB
Plaintext

/* NetRexx */
options replace format comments java symbols binary
import javax.xml.parsers.
import javax.xml.xpath.
import org.w3c.dom.
import org.w3c.dom.Node
import org.xml.sax.
xmlStr = '' -
|| '<inventory title="OmniCorp Store #45x10^3">' -
|| ' <section name="health">' -
|| ' <item upc="123456789" stock="12">' -
|| ' <name>Invisibility Cream</name>' -
|| ' <price>14.50</price>' -
|| ' <description>Makes you invisible</description>' -
|| ' </item>' -
|| ' <item upc="445322344" stock="18">' -
|| ' <name>Levitation Salve</name>' -
|| ' <price>23.99</price>' -
|| ' <description>Levitate yourself for up to 3 hours per application</description>' -
|| ' </item>' -
|| ' </section>' -
|| ' <section name="food">' -
|| ' <item upc="485672034" stock="653">' -
|| ' <name>Blork and Freen Instameal</name>' -
|| ' <price>4.95</price>' -
|| ' <description>A tasty meal in a tablet; just add water</description>' -
|| ' </item>' -
|| ' <item upc="132957764" stock="44">' -
|| ' <name>Grob winglets</name>' -
|| ' <price>3.56</price>' -
|| ' <description>Tender winglets of Grob. Just add priwater</description>' -
|| ' </item>' -
|| ' </section>' -
|| '</inventory>'
expr1 = '/inventory/section/item[1]'
expr2 = '/inventory/section/item/price'
expr3 = '/inventory/section/item/name'
attr1 = 'upc'
do
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(InputSource(StringReader(xmlStr)))
xpath = XPathFactory.newInstance().newXPath()
-- Extract attribute from 1st item element
say expr1
say " "(Node xpath.evaluate(expr1, doc, XPathConstants.NODE)).getAttributes().getNamedItem(attr1)
say
-- Extract and display all price elments
nodes = NodeList xpath.evaluate(expr2, doc, XPathConstants.NODESET)
say expr2
loop i_ = 0 to nodes.getLength() - 1
say Rexx(nodes.item(i_).getTextContent()).format(10, 2)
end i_
say
-- Extract elements and store in an ArrayList
nameList = java.util.List
nameList = ArrayList()
nodes = NodeList xpath.evaluate(expr3, doc, XPathConstants.NODESET)
loop i_ = 0 to nodes.getLength() - 1
nameList.add(nodes.item(i_).getTextContent())
end i_
-- display contents of ArrayList
say expr3
loop n_ = 0 to nameList.size() - 1
say " "nameList.get(n_)
end n_
say
catch ex = Exception
ex.printStackTrace()
end
return