XML文档操作

本文介绍了一个用于操作XML文件的Java类XMLEditor。该类提供了加载XML文件、设置节点属性值、设置节点文本内容、添加新节点及删除节点等功能。通过实例演示了如何使用这些方法来修改XML文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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"); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值