1、创建XML文件
@Test public void testNewDoc() throws Exception{ //创建新的xml文件 Document doc=DocumentHelper.createDocument(); //添加根元素 Element root=doc.addElement("datasource"); //添加根元素属性 root.addAttribute("type","oracle"); //添加子元素和文本 root.addElement("user").addText("orc1"); root.addElement("pwd").addText("123"); FileOutputStream out=new FileOutputStream("out/a.xml"); OutputFormat format=OutputFormat.createPrettyPrint(); XMLWriter writer=new XMLWriter(out,format); writer.write(doc); writer.close(); }
@Test public void testSAXReader() throws Exception{ InputStream in=TestCase.class.getResourceAsStream("contacts.xml"); SAXReader reader=new SAXReader(); Document doc=reader.read(in);//doc是树形数据结构 in.close(); System.out.println(doc.asXML()); }
@Test public void testGetName() throws Exception{ File file=new File("out/contacts.xml"); SAXReader reader=new SAXReader(); Document doc=reader.read(file); Element root=doc.getRootElement(); List<Element> list=root.elements(); Element first=list.get(0); Element name=first.element("name"); String str=name.getText(); System.out.println(str); String s=first.elementTextTrim("name");//和上面两行等价 System.out.println(s); }结果:tom
tom
@Test public void testAttr() throws Exception{ File file=new File("out/books.xml"); SAXReader reader=new SAXReader(); Document doc=reader.read(file); Element root=doc.getRootElement(); List<Element> list=root.elements(); Element book=list.get(0); Attribute attr=book.attribute("language"); System.out.println(attr.getName()); System.out.println(attr.getValue()); }结果:language
CHN
@Test public void testModifyXML() throws Exception{ File file=new File("out/contacts.xml"); SAXReader reader=new SAXReader(); Document doc=reader.read(file); Element root=doc.getRootElement(); Element contact=root.addElement("contact"); contact.addAttribute("id","3"); contact.addElement("name").addText("apple"); contact.addElement("phone").addText("111"); contact.addElement("addr").addText("beijing"); System.out.println(doc.asXML()); FileOutputStream out=new FileOutputStream("out/contacts2.xml"); OutputFormat format=OutputFormat.createPrettyPrint(); XMLWriter writer=new XMLWriter(out,format); writer.write(doc); writer.close(); }