"Sax Parsing XML Notes"

Source: Internet
Author: User

Jdom jarunderDownload Address:Http://files.cnblogs.com/files/yaoxiaoxing/jdom.zip  Test XML file "Create an XML file under Java project src"
  
 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <HD>
  3. <team tname="LARKER">
  4. <playername>KobeBryant</playername>
  5. <playernum>24</playernum>
  6. <position>得分后卫</position>
  7. </team>
  8. <team tname="CLEVELAND">
  9. <playername>LerbonJames</playername>
  10. <playernum>23</playernum>
  11. <position>小前锋</position>
  12. </team>
  13. </HD>
Test class file "Create a class file under Java project src"
  
 
  1. import java.util.List;
  2. import org.jdom.Document;
  3. import org.jdom.Element;
  4. import org.jdom.input.SAXBuilder;
  5. /**
  6. *
  7. * @ClassName: AnalySisXml
  8. * @Description: TODO(sax解析xml文件)
  9. * @author Crayon
  10. * @date 2016年5月6日 下午5:06:59
  11. *
  12. */
  13. public class AnalySisXml {
  14. public static void main(String[] args) throws Exception {
  15. //sax 是一种解析xml的方式
  16. SAXBuilder sb = new SAXBuilder() ;
  17. //通过一个文件构建了一个document对象
  18. Document doc = sb.build(AnalySisXml.class.getClassLoader().getResourceAsStream("test.xml")) ;
  19. //拿到文件的根元素
  20. Element root = doc.getRootElement() ;
  21. //拿到根元素的子元素
  22. List list = root.getChildren("team");
  23. System.out.println("========SAX解析xml文件=========");
  24. //遍历子元素的信息
  25. for(int i=0;i<list.size();i++){
  26. Element element =(Element)list.get(i) ;
  27. String tname = element.getAttributeValue("tname") ;
  28. String playername = element.getChildText("playername") ;
  29. String playernum = element.getChildText("playernum") ;
  30. String position = element.getChildText("position") ;
  31. System.out.println("球队:"+tname);
  32. System.out.println("球员:"+playername);
  33. System.out.println("号码:"+playernum);
  34. System.out.println("司职:"+position);
  35. }
  36. }
  37. }

Post-run results:




From for notes (Wiz)

Sax parsing XML notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.