xml解析2:使用递归解析给定的任意一个xml文档并且将其内容输出到命令行上

前端之家收集整理的这篇文章主要介绍了xml解析2:使用递归解析给定的任意一个xml文档并且将其内容输出到命令行上前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

使用递归解析给定的任意一个xml文档并且将其内容输出到命令行

综合 解析根元素节点,各孩子属性值,并输出

  1. package ytu.botao.xml.dom;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import javax.xml.parsers.DocumentBuilder;
  5. import javax.xml.parsers.DocumentBuilderFactory;
  6. import javax.xml.parsers.ParserConfigurationException;
  7. import org.w3c.dom.Attr;
  8. import org.w3c.dom.Comment;
  9. import org.w3c.dom.Document;
  10. import org.w3c.dom.Element;
  11. import org.w3c.dom.NamedNodeMap;
  12. import org.w3c.dom.Node;
  13. import org.w3c.dom.NodeList;
  14. import org.xml.sax.SAXException;
  15. /**
  16. * 使用递归解析给定的任意一个xml文档并且将其内容输出到命令行上
  17. * @author botao
  18. *
  19. */
  20. public class Demotest2 {
  21. /**
  22. *
  23. * @param args
  24. * @throws ParserConfigurationException
  25. * @throws SAXException
  26. * @throws IOException
  27. */
  28. public static void main(String[] args) throws ParserConfigurationException,SAXException,IOException {
  29. // step 1:获得dom解析器工厂(工厂的作用时用于创建具体的解析器)
  30. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  31. // step 2:获得具体的dom解析器
  32. DocumentBuilder db = dbf.newDocumentBuilder();
  33. // step 3:解析一个xml文档,获得Document对象(根节点)
  34. Document document = db.parse(new File("student.xml"));
  35. // 以上三步为固定模式
  36. //获取根元素节点
  37. Element root=document.getDocumentElement();
  38. parseElement(root);
  39. }
  40. //定义一个静态方法,通过调用方法完成xml解析
  41. private static void parseElement(Element element) {
  42. String tagName=element.getNodeName();
  43. NodeList children=element.getChildNodes();
  44. System.out.print("<"+tagName);
  45. // element元素的所有属性所构成的NamedNodeMap对象,需要对其进行判断
  46. NamedNodeMap map = element.getAttributes();
  47. // 如果该元素存在属性
  48. if (null != map) {
  49. for (int i = 0; i < map.getLength(); i++) {
  50. // 获得该元素的每一个属性
  51. Attr attr = (Attr) map.item(i);
  52. String attrName = attr.getName();
  53. String attrValue = attr.getValue();
  54. System.out.print(" " + attrName + "=\"" + attrValue + "\"");
  55. }
  56. }
  57. System.out.print(">");
  58. for (int i = 0; i < children.getLength(); i++) {
  59. Node node = children.item(i);
  60. // 获得结点的类型
  61. short nodeType = node.getNodeType();
  62. if (nodeType == Node.ELEMENT_NODE) {
  63. // 是元素,继续递归
  64. parseElement((Element) node);
  65. } else if (nodeType == Node.TEXT_NODE) {
  66. // 递归出口
  67. System.out.print(node.getNodeValue());
  68. } else if (nodeType == Node.COMMENT_NODE) {
  69. System.out.print("<!--");
  70. Comment comment = (Comment) node;
  71. // 注释内容
  72. String data = comment.getData();
  73. System.out.print(data);
  74. System.out.print("-->");
  75. }
  76. }
  77. System.out.print("</" + tagName + ">");
  78. }
  79. }

猜你在找的XML相关文章