`
44424742
  • 浏览: 224442 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

JAVA读取XML文件

阅读更多
    本文所讲的内容是有关于Java读取xml文件的相关的内容,文章大致分为三个部分,即Java类、xml文件以及最后的输出结果。
    1. packagecom.java.test;
    2. importorg.w3c.dom.*;
    3. importjavax.xml.parsers.*;
    4. importjava.io.*;
    5. publicclassJavaReadXml{
    6. //Document可以看作是XML在内存中的一个镜像,那么一旦获取这个Document就意味着可以通过对
    7. //内存的操作来实现对XML的操作,首先第一步获取XML相关的Document
    8. privateDocumentdoc=null;
    9. publicvoidinit(StringxmlFile)throwsException{
    10. //很明显该类是一个单例,先获取产生DocumentBuilder工厂
    11. //的工厂,在通过这个工厂产生一个DocumentBuilder,
    12. //DocumentBuilder就是用来产生Document的
    13. DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance();
    14. DocumentBuilderdb=dbf.newDocumentBuilder();
    15. //这个Document就是一个XML文件在内存中的镜像
    16. doc=db.parse(newFile(xmlFile));
    17. }
    18. //该方法负责把XML文件的内容显示出来
    19. publicvoidviewXML(StringxmlFile)throwsException{
    20. this.init(xmlFile);
    21. //在xml文件里,只有一个根元素,先把根元素拿出来看看
    22. Elementelement=doc.getDocumentElement();
    23. System.out.println("根元素为:"+element.getTagName());
    24. NodeListnodeList=doc.getElementsByTagName("person");
    25. System.out.println("book节点链的长度:"+nodeList.getLength());
    26. NodefatherNode=nodeList.item(0);
    27. System.out.println("父节点为:"+fatherNode.getNodeName());
    28. //把父节点的属性拿出来
    29. NamedNodeMapattributes=fatherNode.getAttributes();
    30. for(inti=0;i<attributes.getLength();i++){
    31. Nodeattribute=attributes.item(i);
    32. System.out.println("book的属性名为:"+attribute.getNodeName()
    33. +"相对应的属性值为:"+attribute.getNodeValue());
    34. }
    35. NodeListchildNodes=fatherNode.getChildNodes();
    36. System.out.println(childNodes.getLength());
    37. for(intj=0;j<childNodes.getLength();j++){
    38. NodechildNode=childNodes.item(j);
    39. //如果这个节点属于Element,再进行取值
    40. if(childNodeinstanceofElement){
    41. //System.out.println("子节点名为:"+childNode.getNodeName()+"相对应的值为"+childNode.getFirstChild().getNodeValue());
    42. System.out.println("子节点名为:"+childNode.getNodeName()
    43. +"相对应的值为"+childNode.getFirstChild().getNodeValue());
    44. }
    45. }
    46. }
    47. publicstaticvoidmain(String[]args)throwsException{
    48. JavaReadXmlparse=newJavaReadXml();
    49. //我的XML文件
    50. parse.viewXML("person.xml");
    51. }
    52. }
  • 一.java类

    二.xml文件

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <book>
  3. <person>
  4. <first>wang</first>
  5. <last>laohu</last>
  6. <age>25</age>
  7. <version>中国邮电出版社</version>
  8. </person>
  9. <person>
  10. <first>li</first>
  11. <last>junjia</last>
  12. <age>24</age>
  13. <version>清华大学出版社</version>
  14. </person>
  15. </book>

三.输出结果

根元素为:book
book节点链的长度:2
父节点为:person
9
子节点名为:first相对应的值为wang
子节点名为:last相对应的值为laohu
子节点名为:age相对应的值为25
子节点名为:version相对应的值为中国邮电出版社

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics