解析xml获取所需文本、属性信息

整理一下最近一段时间所使用的如何从xml中获取自己想要的信息
下面是要测试的xml结构

<?xml version="1.0" encoding="UTF-8"?>
<province name="河北省">
    <city name="石家庄市">
        <district name="长安区">这里是长安区</district>
        <district name="新华区">这里是新华区</district>
        <district name="桥东区">这里是市中心</district>
    </city>
    <city name="廊坊市">
        <district name="开发区">这里是开发区</district>
        <district name="广阳区">这里是广阳区</district>
        <district name="安次区">这里是安次区</district>
    </city>
</province>

一、先获取到xml根节点

      File file = new File("C:\\Users\\STEVEN\\Desktop\\测试xml.xml"); 
      SAXReader reader = new SAXReader();
      Document doc = reader.read(file);
      Element root = doc.getRootElement();
      Map<String, Object> testMap = new Test2().getXml(root);

二、获取city的属性值

  public static Map<String, Object> getXml(Document doc){
       Map<String, Object> cityMap = new HashMap<String, Object>();
       Element root = doc.getRootElement();
       for(Element rootCity :(List<Element>)root.elements()){
           //获取“name”属性值
           String name = rootCity.attributeValue("name");
           List<String> district = getDistrict(rootCity);
           cityMap.put(name, district);
       }
       return cityMap;
   }

三、获取district的文本内容

public static List<String> getDistrict(Element rootCity){
       List<String> district = new ArrayList<>();
       for(Element rootDistrict:(List<Element>)rootCity.elements()){
           //获取关于district的描述内容
           String desc = rootDistrict.getText();
           district.add(desc);
       }

总结:无论是取文本信息还是属性信息,方法都是固定的,解析xml最重要的是要理解xml层级结构,一层层的去剖析,问题应该不大。

有兴趣的童鞋还可以看看XPath

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值