springboot下XML解析

需求:互联互通定量评审,通过23个入参XML访问webService,得到相应的出参XML。

  针对入参需要根据前端传入的param替换入参XML模板中特定标识;

  针对出参需要根据出参XML模板中特定标识,找到通过入参XML访问webService后得到的出参XML在该特定标识位置的值,取出来组成一个Object返回给前端。 记录下开发该工具所遇问题,以及解决方案。

question1:获取XML文件内容

answer:springboot中,默认情况只能获取和配置文件同类型资源文件(即properties,yml等),要获取XML类型格式文件,需要在pom文件声明资源文件类型,如下所示。

Resource resource =new ClassPathResource("inputXml/个人基本信息查询.xml");

StringBuffer buffer =new StringBuffer();

try {

BufferedReader br =new BufferedReader(new InputStreamReader(resource.getInputStream(), "utf-8"));

    String line ="";

    while ((line = br.readLine()) !=null) {

buffer.append(line);

    }

br.close();

}catch (Exception e){

e.printStackTrace();

}

String xmlStr =buffer.toString();

System.out.println("inputXml:"+xmlStr);



question2:生成webservice客户端

answer:idea2020版自动生成WebService客户端



question3:通过上述xml获取的参数(xmlStr)作为参数调用webservice,未得到正确的调用结果.

answer:将该xmlStr复制到文档格式化后,发现文档开头有个非法标识符?,仔细对照本地文档并没有该标识符,最后发现是该文档模板在本地保存的是UTF-8-bom编码,而我在java中是用UTF-8编码解析,所以出现该BUG,将该文档模板以UTF-8编码保存后,调用webservice后通过。


question4:解析webservice生成的XML,使用dom4J加上Xpath技术快速找特定标识值,发现代码报错

org.dom4j.XPathException: Exception occurred evaluting XPath: PRPA_IN201306UV02:acknowledgement. Exception: XPath expression uses unbound namespace prefix PRPA_IN201306UV02

需引入如下JAR包,

answer:XML中有特殊命名空间,需要给Document设置对应的命名空间。如下所示


代码写法如下:提供了两种写法,第一种是直接获取XML文档后解析,设置XML命名空间,第二种是通过传入的xmlStr生成Document,设置命名空间


public static MapxmlToObject(String key,String xmlStr){

try {

//            // 读取XML文件

//        Resource resource = new ClassPathResource("outputXml/EMR-PL-04个人基本信息查询.xml");

//        //1.创建SAXBuilder对象

//        SAXReader saxReader = new SAXReader();

//        Document doc =saxReader.read(resource.getInputStream());

//         Map nameSpaceMap =new HashMap();

 //           nameSpaceMap.put("urn", "urn:hl7-org:v3");

//            //设置命名空间

//      saxReader.getDocumentFactory().setXPathNamespaceURIs(nameSpaceMap);

// 字符串转XML

            Document doc = DocumentHelper.parseText(xmlStr);

            Map nameSpaceMap =new HashMap();

            nameSpaceMap.put("urn", "urn:hl7-org:v3");

            //设置命名空间

            DocumentFactory.getInstance().setXPathNamespaceURIs(nameSpaceMap);

            //String xmlName= DictionaryCode.OUTXMLNAME_MAP.get(key);

            Element eleTask = (Element) doc.selectSingleNode("PRPA_IN201306UV02/urn:acknowledgement");

            String typeCode = eleTask.attribute("typeCode").getValue();

            System.out.println(typeCode);

            if("AA".equals(typeCode)){

return OutputXmlUtil.outputXmlToObject4(key,doc);

            }else{

return new HashMap<>();

            }

}catch (Exception e){

e.printStackTrace();

        }

return new HashMap<>();

    }

你可能感兴趣的:(springboot下XML解析)