之前写过几篇关于Java中解析XML文件的方法,不过,感觉不够简单,今天重写了一遍代码,用到的是方法是Dom,其中加入了日志记录功能--Log4j。
好了,不多说了,先把XMl文件贴出来
<?xml version="1.0" encoding="GB2312"?> <EPClientDemo> <WebService_IP>201.55.46.79</WebService_IP> <WebService_PORT>3389</WebService_PORT> <Dest>DLUT</Dest> <RootPath_Receive>F:\rec</RootPath_Receive> <Receiver>研发</Receiver> </EPClientDemo>
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.SAXException; public class ParseXMLTest { private static Logger logger = Logger.getLogger(ParseXMLTest.class.getName()); public void getDemos(InputStream inputStream) throws Exception{ Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("Config.xml"); Element element = document.getDocumentElement(); for(int i = 0; i < element.getElementsByTagName("WebService_IP").getLength(); i++){ System.out.println("<---------共有" + element.getElementsByTagName("WebService_IP").getLength() + "个EPClientDemo--------->"); System.out.println("第" + (i + 1) + "个EPClientDemo:"); System.out.println(" WebService_IP: " + element.getElementsByTagName("WebService_IP").item(0).getTextContent()); System.out.println(" WebService_PORT: " + element.getElementsByTagName("WebService_PORT").item(0).getTextContent()); System.out.println(" Dest: " + element.getElementsByTagName("Dest").item(0).getTextContent()); System.out.println(" RootPath_Receive: " + element.getElementsByTagName("RootPath_Receive").item(0).getTextContent()); System.out.println(" Receiver: " + element.getElementsByTagName("Receiver").item(0).getTextContent()); } } public void update(String index, int count, String value, boolean outOrno) { Document document = null; try { document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("Config.xml"); Element root = document.getDocumentElement(); root.getElementsByTagName(index).item(count).setTextContent(value); output(root, "Config.xml"); if (outOrno) { output(root, null); } } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); logger.error("SAXException error"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); logger.error("IOException error"); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); logger.error("ParserConfigurationException error"); } } //写回XML文件,保存修改或打印到控制台 public static void output(Node node, String filename) { TransformerFactory transFactory = TransformerFactory.newInstance(); try { Transformer transformer = transFactory.newTransformer(); // 设置各种输出属性 transformer.setOutputProperty("encoding", "gb2312"); transformer.setOutputProperty("indent", "yes"); DOMSource source = new DOMSource(); // 将待转换输出节点赋值给DOM源模型的持有者(holder) source.setNode(node); StreamResult result = new StreamResult(); if (filename == null) { // 设置标准输出流为transformer的底层输出目标 result.setOutputStream(System.out); } else { result.setOutputStream(new FileOutputStream(filename)); } // 执行转换从源模型到控制台输出流 transformer.transform(source, result); } catch (TransformerConfigurationException e) { e.printStackTrace(); logger.error("TransformerConfigurationException error"); } catch (TransformerException e) { e.printStackTrace(); logger.error("TransformerException error"); } catch (FileNotFoundException e) { e.printStackTrace(); logger.error("FileNotFoundException error"); } } }
public void update(String index, int count, String value, boolean outOrno)
测试主程序如下:
import java.io.InputStream; import org.apache.log4j.Logger; public class Main_Test { private static Logger logger = Logger.getLogger(Main_Test.class.getName()); /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub read(); update(); } public static void read() { InputStream input = Main_Test.class.getClassLoader().getResourceAsStream("Config.xml"); ParseXMLTest pXmlTest = new ParseXMLTest(); try { pXmlTest.getDemos(input); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); logger.error("Exception error"); } } public static void update(){ ParseXMLTest pXmlTest = new ParseXMLTest(); System.out.println("\n\n尝试修改节点内容中。。。"); pXmlTest.update("WebService_IP", 0, "201.55.46.79", false); pXmlTest.update("WebService_PORT", 0, "3389", false); pXmlTest.update("Dest", 0, "DLUT", false); pXmlTest.update("RootPath_Receive", 0, "F:\\rec", false); pXmlTest.update("Receiver", 0, "研发", true); System.out.println("修改节点内容成功。。。"); } }