1、xml文档或节点转换为字符串百度排名
(1)代码
[java]view plaincopyprint?- //xml文档或节点转换为字符串
- @Test
- publicvoidtest5()throwsException{
- //创建SAXReader对象
- SAXReaderreader=newSAXReader();
- //读取文件转换成Document
- Documentdocument=reader.read(newFile("src/cn/com/yy/dom4j/s.xml"));
- //document转换为String字符串
- StringdocumentStr=document.asXML();
- System.out.println("document字符串:"+documentStr);
- //获取根节点
- Elementroot=document.getRootElement();
- //根节点转换为String字符串
- StringrootStr=root.asXML();
- System.out.println("root字符串:"+rootStr);
- //获取其中student1节点
- Elementstudent1Node=root.element("student1");
- //student1节点转换为String字符串
- Stringstudent1Str=student1Node.asXML();
- System.out.println("student1字符串:"+student1Str);
- }
- document字符串:
- <微信公众号>@残缺的孤独微信公众号>
- <学号>20140101学号>
- <地址>北京海淀区地址>
- <座右铭>要么强大,要么听话座右铭>
- <新浪微博>@残缺的孤独新浪微博>
- <学号>20140102学号>
- <地址>北京朝阳区地址>
- <座右铭>在哭泣中学会坚强座右铭>
- root字符串:
- <微信公众号>@残缺的孤独微信公众号>
- <学号>20140101学号>
- <地址>北京海淀区地址>
- <座右铭>要么强大,要么听话座右铭>
- <新浪微博>@残缺的孤独新浪微博>
- <学号>20140102学号>
- <地址>北京朝阳区地址>
- <座右铭>在哭泣中学会坚强座右铭>
- student1字符串:
- <微信公众号>@残缺的孤独微信公众号>
- <学号>20140101学号>
- <地址>北京海淀区地址>
- <座右铭>要么强大,要么听话座右铭>
- <微信公众号>@残缺的孤独微信公众号>
- <学号>20140101学号>
- <地址>北京海淀区地址>
- <座右铭>要么强大,要么听话座右铭>
- <新浪微博>@残缺的孤独新浪微博>
- <学号>20140102学号>
- <地址>北京朝阳区地址>
- <座右铭>在哭泣中学会坚强座右铭>
(1)代码
[java]view plaincopyprint?- //xml字符串转换为Document对象
- @Test
- publicvoidtest6()throwsException{
- StringxmlStr="
";@残缺的孤独 25沈阳网页设计 软件开发工程师 - Documentdocument=DocumentHelper.parseText(xmlStr);
- //写入emp1.xml文件
- writerDocumentToNewFile(document);
- }
@残缺的孤独 25 软件开发工程师
我们使用dom4j新建document对象,并写入文件中。
(1)代码
[java]view plaincopyprint?- //新建Document对象,添加节点元素并写入文件
- @Test
- publicvoidtest7()throwsException{
- Documentdocument=DocumentHelper.createDocument();
- ElementrootElement=document.addElement("employee");
- ElementempName=rootElement.addElement("empname");
- empName.setText("@残缺的孤独");
- ElementempAge=rootElement.addElement("age");
- empAge.setText("25");
- ElementempTitle=rootElement.addElement("title");
- empTitle.setText("软件开发工程师");
- //写入文档emp.xml
- writerDocumentToNewFile(document);
- }
@残缺的孤独 25 软件开发工程师
从上可以看出,使用dom4j可以很容易的实现xml字符串与document之间的转换,并且创建document对象变得简易。