0

我正在使用以下代码更改 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 包含更改后的表单。现在如何将其转换为字符串,以便可以将新文档传递给其他人。

4

1 回答 1

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();
于 2012-04-12T10:09:59.083 回答