XML文件解析

本文通过使用jdom库解析XML文件,演示了如何获取XML中的班级人数、活动信息及学生个人信息。包括读取XML文件、解析节点、获取属性值、遍历学生列表并收集数据。

XML内容如下:

<students>
<student>
    <name>tom</name>
    <age>19</age>
</student>
<student>
    <name>john</name>
    <age>19</age>
</student>

<count>40</count>

<action name="swim" score="30"></action>
</students>

 

使用jdom解析该XML的代码如下 

  InputStream in = null;
  Map<String, String> map = new HashMap<String, String>();
  try
  {
   in = new FileInputStream("resource/aa.xml");
   
   SAXBuilder builder = new SAXBuilder();
   Document doc = builder.build(in);
   Element root = doc.getRootElement();

   // 获取班级人数

   String count = root.getChild("count").getValue();

   System.out.println(count);

  

   // 获取活动
   Element actionEle = root.getChild("action");
   String actionName = actionEle.getAttribute("name").getValue();
   String score = actionEle.getAttribute("score").getValue();
   Action action = new Action(actionName, score);
   System.out.println(action);

 

   // 获取学生信息

   List<Element> eles = root.getChildren("student");
   String name = "";
   String value = "";
   for (Element el : eles)
   {
    name = el.getChild("name").getValue();
    value = el.getChild("age").getValue();
    map.put(name, value);
   }
  }
  catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   
  }
  finally
  {
   try
   {
    in.close();
   }
   catch (IOException e1)
   {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }
  }
  System.out.println(map);

 }

 

结果为:

40
name=swim; score=30

{john=19, tom=19}

附:

String转InputStream

String aa = "dd";
InputStream is = new ByteArrayInputStream(aa.getBytes());

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值