如果是简单或者标准格式的xml,可以使用xstream,之前映射成一个对象然后去修改操作,很简单。
但是如果是负杂的,而且有可能xml的节点内容不一样,该怎么做呢?
一下是我的一种解决方法,当然可以利用其他的jar包如dom4j等,应该更简单一些
StringReader sr = new StringReader(strXml); InputSource is = new InputSource(sr); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); Document doc = builder.parse(is); NodeList list = doc.getElementsByTagName("extract4DB"); for (int i = 0; i < list.getLength(); i++) { Element ele = (Element) list.item(i); String brandName = ele.getAttribute("name"); if(brandName.equals("ts1")){ NodeList list1 = ele.getElementsByTagName("datasourceNames"); Element ele1 = (Element) list1.item(0); String[] s = ele1.getTextContent().split(";"); ele1.setTextContent(s[0]+"_standby;"); System.out.println(ele1.getTextContent()); } } TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.setOutputProperty("encoding","utf-8"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); t.transform(new DOMSource(doc),new StreamResult(bos)); String xmlchange = bos.toString(); System.out.println(xmlchange);
strXml:是附件中的字符串