Dom通过xpath 获取节点的值

1.首先获取 xml文档

@Test
    public void testXml() {
        
        File file = new File("2.1.1.10值机柜台变更报文.xml");
         
        String strMsg = new String(Utils.readXml(file));
        
         Utils.parserXMl(strMsg);
         
        
    }

2. 将 file 文件 转换成字节数组 作为字符串对象的参数 ,

@Test
    public static byte[] readXml(File file) {

        // File file = new File("2.1.1.10值机柜台变更报文.xml");

        // 将file文件 转成 字节数组 ,
        InputStream in = null;
        byte[] buffer = null;
        try {
            buffer = new byte[(int) file.length()];
            in = new FileInputStream(file);
            DataInputStream din = new DataInputStream(in);
            din.readFully(buffer);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return buffer;

    }

3. 将string 字符串 转换成 dom对象

// 解析 xml 字符串

    public static void parserXMl(String msg) {

        SAXReader sax = new SAXReader();

        try {
            Document doc = sax.read(new ByteArrayInputStream(msg.getBytes()));

            List<Element> list = SelectNodeByDefaultNS(doc, "/AIIS/FLIGHTMOVEMENT/ACTIVEFLIGHT");
            System.out.println(list.size());
            
            Element element = list.get(0);
            Node n = element;
             
            System.out.println(element.elementText("FLIGHTID"));
            
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

4.通过xpath 获取节点的值

 
    @SuppressWarnings("unchecked")
    private static List<Element> SelectNodeByDefaultNS(Document doc, String path) {
        // TODO Auto-generated method stub
        String prefix = "default";
        Namespace ns = doc.getRootElement().getNamespace();
        Map<String,String> map = new HashMap<String,String>();
        map.put(prefix, ns.getURI());
        path = path.replaceAll("/", "/" + prefix + ":");
        XPath xpath = doc.createXPath(path);
        xpath.setNamespaceURIs(map);
        return  xpath.selectNodes(doc);
    }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值