# [java] XPath and XSLT, result to NodeList

## Recommended Posts

Hi I have a XML file: <Scores> <Score> <S1>10</S1> <S2>20</S2> <S3>15</S3> </Score> <Score> ... </Score> ... </Scores> I now use XPath to select "Score" nodes. XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expression = xpath.compile("//Scores/Score"); NodeList list = (NodeList) expression.evaluate(document, XPathConstants.NODESET); Now, I want to apply XSLT on this NodeList (list) to have "S1", "S2" & "S3" sorted like: S1, asc S2, asc S3, desc (I don't have any problem constructing the XSLT) Why do I want to use XSLT then? Because, I want to iterate through the NodeList and print the scores out (best first), without first having to do the sorting manually. Having this NodeList, I want to edit "Result" nodes. (Maximum number of "Score" tags in "Scores" are 3. When a new result is to be inserted, the last entry in the NodeList should be replace with the values of the new score.) Does anyone now how to do this? Btw, is it possible to store the XSLT inside the program and not as a file? Kind Regards

##### Share on other sites
I guess I'm not entirely sure what you're asking. You can sort using XSLT if that is what you're after.

##### Share on other sites
I need to fetch data out from my Document and having the result sorted.
The problem is that I don't know how to apply XSLT on my Document in Java. How to construct XSLT is not a problem.

This is what I've found so far:
 Document document = ...; // Load xml-file to Document. String xsltSource = "..."; Source xslt = new StreamSource(new StringReader(xsltSource)); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(xslt); t.transform(new DOMSource(document), new StreamResult(new FileOutputStream("XSLTresult.xml")));

But I want to have the result in a NodeList (or something), so that I can iterate through them (and print them out).

Now I have to do this:
2. Apply XSLT to document (result is saved to xml-file).
4. Load this xml-file to Document.
5. Print results

Isn't there a shorter way of how to do this?
Maybe something like:
2. Apply XSLT to document (result in another Document object)
3. Print results

Kind Regards

[Edited by - CodeMachine on October 7, 2006 6:48:47 AM]

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628301
• Total Posts
2981913

• 10
• 11
• 11
• 10
• 10