0

I'm trying with this attempt to produce an xml based on the one given, joining values of same TagName. For example this is what I've done so far:

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class TestXPath {

    public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException {
         String xml =
                    "<ROOT>" +
                    "    <coolnessId>9</coolnessId>" +
                    "    <cars id=\"3\">0</cars>" +
                    "    <cars id=\"2\">1</cars>" +
                    "    <cars id=\"1\">2</cars>" +
                    "</ROOT>";

                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setNamespaceAware(true);

                Document doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
                XPath xpath = XPathFactory.newInstance().newXPath();

               ///XPathExpression expr = xpath.compile("concat(//ROOT/cars,'-',//ROOT/coolnessId)");//concat(//ROOT/cars)
                XPathExpression expr = xpath.compile("concat(//ROOT/cars,'-')");//concat(//ROOT/cars)
                // XPathExpression expr = xpath.compile( "concat(//*[contains(name(), 'cars')],'')");
            System.out.println(expr.evaluate(doc, XPathConstants.STRING)); 
    }
}

This code produces:

0-

Now this is what should be:

2-1-0

As you can see the values follow the attribute "id" of each "cars" tag. I've rearrenged many times but can't achieve my result. Please keep in mind I'm on a very old enviroment such as Java 1.4 runtime.

1
  • See here for XPath 1.0 answer. In XPath 2.0 you could use string-join instead of concat. Commented May 20, 2020 at 19:07

1 Answer 1

0

I think it's going to be simplest to retrieve the nodes using XPath, and then concatenate the string values in Java code.

Any other solution involves upgrading your technology: XSLT, XPath 2.0+, etc, and that isn't going to be easy on a JDK 1.4 platform.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.