XML文件操作
发布时间:2020-12-15 22:35:52 所属栏目:百科 来源:网络整理
导读:1、创建XML文件 @Testpublic void testNewDoc() throws Exception{//创建新的xml文件Document doc=DocumentHelper.createDocument();//添加根元素Element root=doc.addElement("datasource");//添加根元素属性root.addAttribute("type","oracle");//添加子元
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 3、修改XML文件 @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(); }
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 正则表达式替换为C#
- swift2 – 使用Swift 2中的split功能
- SQLite指南(5) - PRAGMA命令用法(完整)
- swift与OC之间不得不知道的21点
- xml – 创建动态视图,多次视图X次,获取/设置每个组的值
- react+webpack+antd框架自定义使用阿里iconfont图标。
- actionscript-3 – 我为什么要使用MXML?
- .net reactor 学习系列(五)---.net reactor针对De4Dot脱壳工
- React-native 知识点-this.bind-返回键-React.cloneElement
- JRuby 1.7.1和PsychParser错误解析UTF-8 YAML文件(Rails 3.