解析xml

package com.laiwei.lwiot.controller.bean;

import org.junit.Test;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.File;

/**
 * Created by lw-yf-020 on 2017/3/10.
 */
public class XPathTest {
    @Test
    public void test() throws Exception{
        // 解析文件,生成document对象
        DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder();
        org.w3c.dom.Document document = builder.parse(new File("C:\\Users\\lw-yf-020\\Desktop\\test.xml"));
        // 生成XPath对象
        XPath xpath = XPathFactory.newInstance().newXPath();

            String expression = "/jetData/site/client/*";
         //type下节点
            NodeList nodeList = (NodeList) xpath.compile(expression).evaluate(document, XPathConstants.NODESET);
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node nNode = nodeList.item(i);
                Element element=(Element) nNode;
                System.out.println(nNode.getNodeName()+":"+element.getAttribute("dataType"));
                NodeList nodeList1=   element.getElementsByTagName("point");
                //type下的元素
                for (int j=0;j<nodeList1.getLength();j++){
                  Node node=  nodeList1.item(j);
                    Element element1=(Element) node;
                    System.out.println("pointId:"+element1.getAttribute("pointId")+"\t"+"pointName:"+element1.getAttribute("pointName")+"\t"+"context:"+element1.getTextContent());
                }


            }




        }



    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值