dom4j selectNodes 取不到值 因为XML带有命名空间 HL7
Dom4j 保存XML
String xmlPath = "D:\\BS004.xml"; String savePath = "D:\\BS004_save.xml"; SAXReader reader = new SAXReader(); Document doc = reader.read(xmlPath); //添加命名空间 Map<String, String> xmlMap = new HashMap<>(); xmlMap.put("s", "urn:hl7-org:v3"); //作用域在文档上,方便多次 select Node reader.getDocumentFactory().setXPathNamespaceURIs(xmlMap); //消息创建时间 Node creationTimeNode = doc.selectSingleNode("/s:POOR_IN200901UV/s:creationTime/@value"); creationTimeNode.setText(DateUtil.format(new Date(), "yyyyMMddHHmmss")); Element locationNode = (Element) doc.selectSingleNode("/s:POOR_IN200901UV/s:controlActProcess/s:subject/s:placerGroup/s:componentOf1/s:encounter/s:location"); Document ss = DocumentHelper.parseText(locationNode.asXML()); locationNode.addText("转成 Element 对象,进行操作"); OutputFormat outputFormat = OutputFormat.createPrettyPrint(); outputFormat.setEncoding("UTF-8"); XMLWriter writer = null; try { writer = new XMLWriter(new FileWriter(savePath), outputFormat); writer.write(doc); writer.flush(); writer.close(); } catch (Exception e) { e.printStackTrace(); }