一、例子
public class XMLUtils { /** * 生成xml文件 * @param doc * @param fileName * @param encoding */ public static void createXMLFile(Document doc,String fileName,String encoding){ XMLWriter writer = null; try{ if(StringUtils.isNotEmpty(encoding)){ OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(encoding); // 指定XML编码 writer = new XMLWriter(new FileWriter(fileName),format); }else{ writer = new XMLWriter(new FileWriter(fileName)); } writer.write(doc); }catch(IOException e){ e.printStackTrace(); }finally{ try{ writer.close(); }catch(IOException e){ e.printStackTrace(); } } } /** * 创建Document并返回根结点 * @param root_label 根标签 * @return */ public static Document createDocument(String root_label){ Document doc = DocumentHelper.createDocument(); doc.setRootElement(doc.addElement(root_label)); return doc; } /** * 将字符串转化为XML * @param xml_string * @return */ public static Document createDocumentFromXmlString(String xml_string){ if(StringUtils.isEmpty(xml_string)){ xml_string = "<students> <class>test</class> </students>"; } Document document = null; try { document = DocumentHelper.parseText(xml_string); } catch (DocumentException e) { e.printStackTrace(); } return document; } /** * 给结点加子结点 * @param root 相对根 * @param newNode 新结点 * @param nodeId 结点Id * @param elements 结点元素 */ public static void addNodeElement(Element root,String newNode,String nodeId,Map elements){ Element _newNode = root.addElement(newNode); _newNode.addAttribute("id", nodeId).addAttribute("no", nodeId);//设置属性 Iterator it = elements.entrySet().iterator(); while(it.hasNext()){//结点下的元素与值 Map.Entry entry = (Map.Entry)it.next(); Object key = entry.getKey(); Object value = entry.getValue(); _newNode.addElement((String)key).setText((String)value); } } /** * 将文档或节点的XML转化为字符串 * @param filePath * @return */ public static String readXMLAsString(String filePath){ SAXReader reader = new SAXReader(); Document document=null; try { document = reader.read(new File(filePath)); //Element root=document.getRootElement(); } catch (DocumentException e) { e.printStackTrace(); } return document.asXML(); } /** * 打印节点的所有子节点 * @param element */ public static void printAllChildNode(Element element){ //循环当前节点属性 Iterator attrs = element.attributeIterator(); while(attrs.hasNext()){ Attribute attr = (Attribute)attrs.next(); System.out.println(attr.getName() + "=" + attr.getText()); } //循环其孩子元素节点 Iterator elements = element.elementIterator(); while(elements.hasNext()){ Element ele = (Element)elements.next(); if(ele.attribute("id") == null){ System.out.println(ele.getName() + "=" + ele.getText()); } //递归调用 printAllChildNode(ele); } } /*** * 以xpath读取数据 * @param filePath * @param xpath */ public static void printElementsByXPath(String filePath,String xpath){ SAXReader reader = new SAXReader(); try{ Document doc = reader.read(new File(filePath)); List properties=doc.selectNodes(xpath); Iterator it=properties.iterator(); while(it.hasNext()){ Element elm=(Element)it.next(); System.out.println(elm.getText()); } } catch(Exception ex){ ex.printStackTrace(); } } public static void main(String[] args){ Map<String,String> elements = new HashMap<String,String>(); elements.put("name", "张三"); elements.put("sex", "男"); elements.put("age", "20"); Document doc = XMLUtils.createDocumentFromXmlString("<students></students>"); doc.getRootElement().addAttribute("year", "2000"); XMLUtils.addNodeElement(doc.getRootElement(), "student", "20090313001", elements); elements.clear(); elements.put("name", "李四"); elements.put("sex", "男"); elements.put("age", "21"); XMLUtils.addNodeElement(doc.getRootElement(), "student", "20090313002", elements); String filePath = "D:/test.xml"; XMLUtils.createXMLFile(doc, filePath, "GBK"); //System.out.println(XMLUtils.readXMLAsString(filePath)); XMLUtils.printElementsByXPath(filePath, "/students/student[@id=\"20090313001\"]/name"); XMLUtils.printAllChildNode(doc.getRootElement()); } }
二、使用XPATH
<AAA> <BBB/> <CCC/> <BBB/> <BBB/> <DDD> <BBB/> </DDD> <CCC/> </AAA>
(1)如果它是以斜线“/”开始,它是描述请求元素的绝对路径。
范例结构:
(2)如果路径表达式以“//”开始,它会查找所有符合规则的元素
范例结构:
(3)“*”选择所有由前面路径定位的元素
范例:
(4)在方括号中的表达式可以进一步的指定元素,方括号中的数字表示被选择元素集合的位置,last()函数表示被选择元素集的最后一个元素
(5)“@”表示属性
<AAA> <BBB id = "b1"/> <BBB id = "b2"/> <BBB name = "bbb"/> <BBB/> </AAA>
(6)属性的值可以做为选择标准,函数“normalize-space”可以移掉头部和尾部的空格,或者用单个的空格替换
<AAA> <BBB id = "b1"/> <BBB name = " bbb "/> <BBB name = "bbb"/> </AAA>
(7)函数count(*):计算选择元素的个数