public class XMLEditor {private Document doc;private String fileName;public XMLEditor() {// TODO Auto-generated constructor stub}public XMLEditor(String fileName) {try { // Create a builder factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); // Create the builder and parse the file doc = factory.newDocumentBuilder().parse(new File(fileName)); // Save file name this.fileName = fileName; } catch (SAXException e) { } catch (ParserConfigurationException e) { } catch (IOException e) { }}public XMLEditor(InputStream stream) {try { // Create a builder factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); // Create the builder and parse the file doc = factory.newDocumentBuilder().parse(stream); // Save file name this.fileName = null; } catch (Exception e) { e.printStackTrace(); } }public XMLEditor(Document doc) {try { // Create the builder and parse the file this.doc = doc; // Save file name this.fileName = null; } catch (Exception e) { e.printStackTrace(); } }/** * 設定指定節點的屬性值 * * @param xPath-節點路徑 * @param attrName 屬性名稱 * @param attrValue 屬性值 */public void setNodeAttr(String xPath, String attrName, String attrValue) {try { // Get the matching elements NodeList nodelist = XPathAPI.selectNodeList(doc, xPath); // Process the elements in the nodelist for (int i=0; i<nodelist.getLength(); i++) { // Get element Element elem = (Element)nodelist.item(i); elem.setAttribute(attrName, attrValue); } // save save(); } catch (javax.xml.transform.TransformerException e) { }}/** * 設定節點的常值內容 * * @param xPath-節點的路徑 * @param textValue 節點的常值內容 * @return */public void setNodeText(String xPath, String textValue) {try { // Get the matching elements NodeList nodelist = XPathAPI.selectNodeList(doc, xPath); // Process the elements in the nodelist for (int i=0; i<nodelist.getLength(); i++) { // Get element Element elem = (Element)nodelist.item(i); elem.appendChild(doc.createTextNode(textValue)); } // save save(); } catch (javax.xml.transform.TransformerException e) { }}/** * 添加一個新節點 * * @param xPath 父節點路徑 * @param nodeName 建立節點名稱 * @param attrMap 屬性集合 * @param nodeText 節點包括的常值內容 * @return */public void addChildNode(String xPath, String nodeName, HashMap attrMap, String nodeText) {try { // Get the matching elements NodeList nodelist = XPathAPI.selectNodeList(doc, xPath); // Process the elements in the nodelist for (int i=0; i<nodelist.getLength(); i++) { // Get element Element elem = (Element)nodelist.item(i); Element elem1 = doc.createElement(nodeName); if (attrMap!=null && attrMap.size()>0) {for (Iterator its=attrMap.keySet().iterator();its.hasNext();) {String strKey = (String) its.next();elem1.setAttribute(strKey, attrMap.get(strKey)==null?"":attrMap.get(strKey).toString());}} if (nodeText!=null && nodeText.length()>0) { Text text = doc.createTextNode(nodeText); elem1.appendChild(text);} elem.appendChild(elem1); } // save save(); } catch (javax.xml.transform.TransformerException e) { }}/** * 刪除指定路徑和包括文本的節點 * * @param xPath節點的路徑 * @param nodeText 節點包括的文本,為null時不判斷文本 */public void removeChildNode(String xPath, String nodeText) {try { NodeList nodelist = XPathAPI.selectNodeList(doc, xPath); for (int j = 0; j < nodelist.getLength(); j++) { Node n01 = nodelist.item(j);if (nodeText!=null) {Text t01 = (Text) n01.getFirstChild();if (t01!=null && t01.getData() != null && t01.getData().equals(nodeText)) {Node parent = n01.getParentNode();parent.removeChild(n01);}} else {Node parent = n01.getParentNode();parent.removeChild(n01);} } // save save(); } catch (javax.xml.transform.TransformerException e) { }}public NodeList getNodeList(String xPath){try { return XPathAPI.selectNodeList(doc, xPath); } catch (javax.xml.transform.TransformerException e) { } return null;}private void save() {FileOutputStream fout = null;
try {
// Prepare the DOM document for writing
Source source = new DOMSource(doc);
// Prepare the output file
File file = null;
fileName = null;
if (fileName==null) {
file = File.createTempFile(System.currentTimeMillis()+"", ".xml");
} else {
file = new File(fileName);
}
fout = new FileOutputStream(file);
Result result = new StreamResult(fout); // 要及時關閉輸出資料流
// Write the DOM document to the file
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);
System.out.println("Save to "+ file.getPath());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fout!=null) {
fout.close();
fout=null;
}
} catch (Exception e) {
e.printStackTrace();
}
}}/** * @param args */public static void main(String[] args) {//XMLEditor xe = new XMLEditor("E:/eclipse_all_in_one_2.2.0/workspace_for_birt/org.eclipse.datatools.connectivity.oda.esoon/src/org/eclipse/datatools/connectivity/oda/esoon/impl/xe.xml");System.out.println("00000000000000000000");String fileName = "c:/reportModels.xml";XMLEditor xe = new XMLEditor(fileName);//xe.setAttribute("/Models/Model", "sqlScript", "9999");//HashMap map = new HashMap();//map.put("a1", "a01");//map.put("a2", "a02");//map.put("a3", "a03");//map.put("a4", "a04");//xe.addChildNode("/Models/Model/Field", "ftt",map,"hello world!");HashMap map1 = new HashMap();map1.put("a1", "a01");map1.put("a2", "a02");map1.put("a3", "a03");map1.put("a4", "a04");xe.removeChildNode("/Models/Model/Field/ftt",null);System.out.println("11111111111111111111");}}