要将解析的 XML 转换回字符串,可以使用javax.xml.transform.Transformer
. 我附上了解析您的示例 XML 并将所有D
元素打印到控制台的代码 - 我认为您将能够将其变成您想要的 :)
// The below is simply to create a document to test the code with
String xml = "<A><B><C>stuff</C><D><E>other stuff</E><F>more stuff</F></D></B><B><C>stuff</C></B><B><C>some stuff</C><D><E>basic stuff</E><F>even more stuff</F></D></B></A>";
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource docSource = new InputSource(new StringReader(xml));
Document document = documentBuilder.parse(docSource);
// The above is simply to create a document to test the code with
// Transformer takes a DOMSource pointed at a Node and outputs it as text
Transformer transformer = TransformerFactory.newInstance().newTransformer();
// Add new lines for every element
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// Skip the <? xml ... ?> prolog
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
NodeList elements = document.getElementsByTagName("D");
StringWriter sw = new StringWriter();
StreamResult res = new StreamResult(sw);
DOMSource source = new DOMSource();
for (int i = 0; i < elements.getLength(); i++) {
Element element = (Element) elements.item(i);
source.setNode(element);
// Write the current element to the stringwriter via the streamresult
transformer.transform(source, res);
}
System.out.println(sw.toString());
如果你只想要元素的内容,你可以像这样替换 for 循环:
for (int i = 0; i < elements.getLength(); i++) {
Element element = (Element) elements.item(i);
NodeList childNodes = element.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Node childNode = childNodes.item(j);
source.setNode(childNode);
transformer.transform(source, res);
}
}