我正在尝试根据给定的xml生成xml,连接相同TagName的值。 例如,这是我到目前为止所做的:
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));
}
}
此代码生成:
0-
现在这应该是:
2-1-0
如您所见,这些值遵循每个"cars"标签的属性"id"。 我已经重新整理了很多次,但无法达到我的结果。 请记住,我使用的是非常古老的环境,例如Java 1.4运行时。
我认为使用 XPath 检索节点,然后在 Java 代码中连接字符串值是最简单的。
任何其他解决方案都涉及升级您的技术:XSLT,XPath 2.0+等,这在JDK 1.4平台上并不容易。