<?xml version="1.0" encoding="UTF-8" standalone="no"?> <services> <service id="1001" name="a服务"> <url>http://192.168.1.1:8080/PublicInfo/</url> <state/> </service> <service id="1002" name="b服务"> <url>http://192.168.1.2:8080/ETCMessageService</url> <state/> </service> </services>
上面是本次要解析的XML文件。
package cn.microvideo.info.util; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import cn.microvideo.info.domain.ServiceMonitorInfo; /** * * @author zhouhy * */ public class XMLUtil { private XPath xpath = XPathFactory.newInstance().newXPath(); private Logger log = Logger.getLogger(XMLUtil.class); /** * 获取所有监控服务 * @param document * @param value * @return */ public List<ServiceMonitorInfo> getServices(Document document) { List<ServiceMonitorInfo> services = new ArrayList<ServiceMonitorInfo>(); NodeList nodelist = document.getElementsByTagName("service"); for (int i = 0; i < nodelist.getLength(); i++) { ServiceMonitorInfo service = new ServiceMonitorInfo(); Element serviceNode = (Element) nodelist.item(i); String serviceName = serviceNode.getAttribute("name"); String id = serviceNode.getAttribute("id"); String url = null; String state = null; NodeList listnode = serviceNode.getChildNodes(); for (int j = 0; j < listnode.getLength(); j++) { Node nd = listnode.item(j); if("url".equals(nd.getNodeName())){ url = nd.getTextContent(); }else if("state".equals(nd.getNodeName())){ state = nd.getTextContent(); } } service.setServiceName(serviceName); service.setUrl(url); service.setState(state); service.setId(id); services.add(service); } return services; } /** * 根据ID查询服务 * @param document * @param value * @return */ public ServiceMonitorInfo findNodeByAttrValue(Document document, String code) { if(StringUtils.isBlank(code)){ return null; } ServiceMonitorInfo service = new ServiceMonitorInfo(); NodeList nodelist = document.getElementsByTagName("service"); // 遍历 for (int i = 0; i < nodelist.getLength(); i++) { Element serviceNode = (Element) nodelist.item(i); String val = serviceNode.getAttribute("id"); if(code.equals(val)){ String serviceName = serviceNode.getAttribute("name"); String id = serviceNode.getAttribute("id"); String url = null; String state = null; NodeList listnode = serviceNode.getChildNodes(); for (int j = 0; j < listnode.getLength(); j++) { Node nd = listnode.item(j); if("url".equals(nd.getNodeName())){ url = nd.getTextContent(); }else if("state".equals(nd.getNodeName())){ state = nd.getTextContent(); } } service.setServiceName(serviceName); service.setUrl(url); service.setState(state); service.setId(id); } } return service; } /** * 删除某个节点对象 * @param document * @param id * @throws TransformerException * @throws XPathExpressionException * @throws UnsupportedEncodingException */ public void deleteNodeById(Document document, ServiceMonitorInfo serviceInfo) throws TransformerException, XPathExpressionException, UnsupportedEncodingException { NodeList services = (NodeList) xpath.evaluate("//service[@id='"+serviceInfo.getId()+"']", document, XPathConstants.NODESET); Node node = services.item(0); if(node != null){ node.getParentNode().removeChild(node); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); URL url = Thread.currentThread().getContextClassLoader().getResource("cn/microvideo/info/config/servicemonitor.xml"); String path =URLDecoder.decode(url.getPath(),"UTF-8"); log.info("删除服务监控:"+serviceInfo.toString()); transformer.transform(new DOMSource(document), new StreamResult( new File(path))); } } /** * 更新某个节点 * @param document * @param id * @throws TransformerException * @throws XPathExpressionException * @throws UnsupportedEncodingException */ public void updateNodeById(Document document, ServiceMonitorInfo serviceInfo) throws TransformerException, XPathExpressionException, UnsupportedEncodingException { NodeList services = (NodeList) xpath.evaluate("//service[@id='"+serviceInfo.getId()+"']", document, XPathConstants.NODESET); Element node = (Element) services.item(0); if(node == null){ addNode(document, serviceInfo); } NodeList nodelist = node.getChildNodes(); for (int i = 0; i < nodelist.getLength(); i++) { Node n = nodelist.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { if (n.getNodeName().equals("url")) { n.setTextContent(serviceInfo.getUrl()); } else if (n.getNodeName().equals("state")) { n.setTextContent(serviceInfo.getState()); } } } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); URL url = Thread.currentThread().getContextClassLoader().getResource("cn/microvideo/info/config/servicemonitor.xml"); String path =URLDecoder.decode(url.getPath(),"UTF-8"); log.info("修改服务监控:"+serviceInfo.toString()); transformer.transform(new DOMSource(document), new StreamResult( new File(path))); } /** * 在指定的节点下方添加新得某个节点 * @param document * @param id * @throws TransformerException * @throws XPathExpressionException * @throws UnsupportedEncodingException */ public void addNode(Document document, ServiceMonitorInfo serviceInfo) throws TransformerException, XPathExpressionException, UnsupportedEncodingException { NodeList nodelist = (NodeList) xpath.evaluate("//service[@id='"+serviceInfo.getId()+"']", document, XPathConstants.NODESET); Element node = (Element) nodelist.item(0); if(node != null){ updateNodeById(document, serviceInfo); return; } Element parentNode = document.getDocumentElement(); Element nd = document.createElement("service"); nd.setAttribute("name", serviceInfo.getServiceName()); nd.setAttribute("id", serviceInfo.getId()); Node url = document.createElement("url"); url.appendChild(document.createTextNode(serviceInfo.getUrl())); Node state = document.createElement("state"); state.appendChild(document.createTextNode(serviceInfo.getState())); nd.appendChild(url); nd.appendChild(state); parentNode.appendChild(nd); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); URL resource = Thread.currentThread().getContextClassLoader().getResource("cn/microvideo/info/config/servicemonitor.xml"); String path =URLDecoder.decode(resource.getPath(),"UTF-8"); log.info("增加服务监控:"+serviceInfo.toString()); transformer.transform(new DOMSource(document), new StreamResult( new File(path))); } public Document getDocument() throws ParserConfigurationException, SAXException, IOException, TransformerException, XPathExpressionException { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("cn/microvideo/info/config/servicemonitor.xml"); Document document = builder.parse(is); return document; } public static void main(String[] args) { XMLUtil xml = new XMLUtil(); try { ServiceMonitorInfo serviceInfo = new ServiceMonitorInfo(); serviceInfo.setId("1003"); serviceInfo.setServiceName("中心数据库"); serviceInfo.setState("正常"); serviceInfo.setUrl("http://demo.cn"); xml.addNode(xml.getDocument(), serviceInfo); } catch (ParserConfigurationException | SAXException | IOException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } } }