首页 > 学院 > 开发设计 > 正文

Java Dom4j XML用法总结

2019-11-15 00:57:23
字体:
来源:转载
供稿:网友
java Dom4j xml用法总结

1、新建XML文档:

Documentdoc= DocumentHelper.createDocument();Element root = doc.addElement("ocs");root.addElement("header");Element body = root.addElement("body");Element fontnode = body.addElement("font");fontnode.addAttribute("size","9");System.out.PRintln(root.asXML());2、打开现有XML文档(从字符串导入): Document doc = DocumentHelper.parseText(XMLStr);Node node = doc.selectSingleNode("ocs/body/font");if(nodeinstanceofElement){Element pnode = (Element) node;Attribute attr = pnode.attribute("size");System.out.println(attr.asXML());} Dom4j中内置了XPath,因此可以在selectSingleNode中象XPath那样访问路径字符串; 注意:需要引用jaxen-1.1.1.jar包,否则selectSingleNode会产生异常并返回Null;3、打开现有文档(从文件导入): SAXReader saxReader =newSAXReader(); Document document = saxReader.read(XMLFile);4、将Document写入到文件中: try{XMLWriter output =newXMLWriter(newFileWriter(newFile(XMLFile)));output.write(doc);output.close();}catch(IOException e){System.out.println(e.getMessage());}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表