String类型的字符串转换成XML对象并获取根节点

前提字符串类型的字符串需要具备XML格式,才能转换

导包:

串类型的字符串(数据):

        //data为String类型的字符串,如上图所示
		String data = getXmlData(request);
		System.out.println(data);

		
	//得到根节点的值
	SAXReader saxReader = new SAXReader();  
        Document document = null; 
        String rootName = null;
        try {
            //将String类型的字符串转换成XML文本对象
            document = saxReader.read(new ByteArrayInputStream(data.getBytes())); 
            
            //得到根节点对象
            Element rootElements = document.getRootElement();
            //得到根节点的节点名称
            System.out.println(rootElements.getName());
            
            //通过根节点得到第一个子节点对象
            Element sonElements =  (Element) rootElements.elements().get(0);
            
            //得到子节点的节点名称
            System.out.println(sonElements.getName());

            
            //通过根节点得到子节点标签为businessType的值
            String sonVal = rootElements.elementText("businessType");
            system.out.println(sonVal);

            //判断是否得到根节点,如果得到,就输出更节点的名字
            if(rootName.equals("certApplyRequest")){
            	System.out.println(rootName);
            }

        } catch (DocumentException e) {
            e.printStackTrace();  
        }

猜你喜欢

转载自blog.csdn.net/qq_37385585/article/details/81502147