w3c.dom写xml文件时候 如果对Element元素进行操作,而将该Element赋给另一个document元素时候,会报错:
org.w3c.dom.DOMException:WRONG_DOCUMENT_ERR:Anodeisusedinadifferentdocumentthantheonethatcreatedit.
public static void sendAlarm(List<Element> elements) { if(elements != null && !elements.isEmpty()){ ObjectOutputStream oos = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbf.newDocumentBuilder(); Transformer transformer = TransformerFactory.newInstance().newTransformer(); oos = new ObjectOutputStream(new Socket(host,port).getOutputStream()); transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8"); for (Element element : elements){ Document doc = builder.newDocument(); <strong><span style="font-size:18px;color:#339999;">doc.appendChild(doc.importNode(element,true));</span></strong> //document 转 string ByteArrayOutputStream bos = new ByteArrayOutputStream(); transformer.transform(new DOMSource(doc),new StreamResult(bos)); String xmlStr = bos.toString(); log.info(xmlStr); oos.writeObject(xmlStr); oos.flush(); } } catch (Exception e) { e.printStackTrace(); } finally { if(oos != null) { try { oos.close(); } catch (IOException e) { e.printStackTrace(); } } } } }即可