XML文檔操作

來源:互聯網
上載者:User
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");}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.