Dom4j原样读取XML

来源:互联网 发布:邓紫棋的喜欢你 知乎 编辑:程序博客网 时间:2024/06/05 05:15
Demo:
  1. package com.dom4j.red;
  2. import java.io.File;
  3. import java.util.Iterator;
  4. import java.util.List;
  5. import org.dom4j.Attribute;
  6. import org.dom4j.Document;
  7. import org.dom4j.DocumentException;
  8. import org.dom4j.Element;
  9. import org.dom4j.Node;
  10. import org.dom4j.Text;
  11. import org.dom4j.io.SAXReader;
  12. /**
  13. * 完整的读取xml的内容
  14. * @author zhiyong
  15. *
  16. */
  17. public class Demo3 {
  18. //定义变量存放
  19. public static StringBuilder sb = new StringBuilder();
  20. public static void main(String[] args) throws DocumentException {
  21. //创建xml解析器对象
  22. SAXReader reader = new SAXReader();
  23. //读取xml文档,返回Document对象
  24. Document document = reader.read(new File("./src/contact.xml"));
  25. //读取根标签下的所有子标签
  26. Element rootEle = document.getRootElement();
  27. String str = getChildNodes(rootEle);
  28. System.out.println(str);
  29. }
  30. /**
  31. * 获取当前标签下的所有子标签
  32. * @param ele
  33. */
  34. public static String getChildNodes(Element ele){
  35. //开始标签
  36. sb.append("<" + ele.getName());
  37. //获取属性
  38. List<Attribute> attList = ele.attributes();
  39. for(Attribute att : attList){
  40. String attName = att.getName();
  41. String attValue = att.getValue();
  42. sb.append(" " + attName + "=\"" + attValue + "\"");
  43. }
  44. sb.append(">");
  45. //获取传入标签下的直接子节点
  46. Iterator<Node> it = ele.nodeIterator();
  47. while(it.hasNext()){
  48. Node node = it.next();
  49. //标签
  50. if(node instanceof Element){
  51. Element n = (Element)node;
  52. getChildNodes(n);
  53. }
  54. //文本
  55. if(node instanceof Text){
  56. Text t = (Text)node;
  57. sb.append(t.getText());
  58. }
  59. }
  60. //结束标签
  61. sb.append("</" + ele.getName() + ">");
  62. return sb.toString();
  63. }
  64. }
xml文件
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <contactList>
  3. <contact id="001" att1="属性值1">
  4. <name>木丁西<nameNode>小刘</nameNode></name>
  5. <age>18</age>
  6. <phone>18071897425</phone>
  7. <email>1012421396@qq.com</email>
  8. <qq>1012421396</qq>
  9. </contact>
  10. <木丁西>
  11. 这是个什么鬼。
  12. </木丁西>
  13. <contact id="002">
  14. <name>刘先森</name>
  15. <age>20</age>
  16. <phone>18771897466</phone>
  17. <email>561242139@qq.com</email>
  18. <qq>561242139</qq>
  19. </contact>
  20. <abc>
  21. </abc>
  22. </contactList>

效果:


0 0
原创粉丝点击