我正在使用以下代码更改xml文档:
DocumentBuilderFactory fty1 = DocumentBuilderFactory.newInstance();
fty1.setNamespaceAware(true);
DocumentBuilder builder1 = fty1.newDocumentBuilder();
ByteArrayInputStream bais1 = new ByteArrayInputStream(tr1.getBytes());//tr1=xml string
Document xmldoc1=builder1.parse(bais1);
xmldoc1.getElementsByTagName("userID").item(0).setTextContent("123123132");
xmldoc1包含更改的表单。现在如何将它转换为字符串,以便新的doument可以传递给其他人。
答案 0 :(得分:4)
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(xmldoc1);
transformer.transform(source, result);
String xmlString = sw.toString();