/** * 组装测试报文 * @param serviceId * @param serviceTime * @return */ public static String getXmlInfo(String serviceId, String serviceTime) { //定义一个XML文档对象 Document document = DocumentHelper.createDocument(); // 文档增加节点,即根节点,一个文档只能有一个根节点,多加出错 Element root = document.addElement("Service"); // 添加注释 //root.addComment("报文头"); // 根节点下添加节点 Element first = root.addElement("Service_Header"); // 节点添加属性 //first.addAttribute("index", "01"); // 节点下添加节点 Element service_sn = first.addElement("service_sn"); Element service_id = first.addElement("service_id"); Element branch_id = first.addElement("branch_id"); Element requester_id = first.addElement("requester_id"); Element channel_id = first.addElement("channel_id"); Element version_id = first.addElement("version_id"); Element service_time = first.addElement("service_time"); // 节点设置内容数据 service_sn.setText("000000000000000000"); service_id.setText(serviceId); branch_id.setText("810101011"); requester_id.setText("test"); channel_id.setText("001"); version_id.setText("01"); service_time.setText(serviceTime); // 创建格式化类,默认生成的XML文件排版格式比较乱,可以通过OutputFormat类格式化输出 // 默认采用createCompactFormat()显示比较紧凑,最好使用createPrettyPrint() OutputFormat outputFormat = OutputFormat.createPrettyPrint(); outputFormat.setIndent(" "); outputFormat.setIndentSize(4); StringWriter formatXml = new StringWriter(); // 创建xml输出流 XMLWriter writer = new XMLWriter(formatXml, outputFormat); try { writer.write(document); } catch (IOException e) { e.printStackTrace(); } return formatXml.toString(); }
/** * 解析resources下的XML文件 */private static void readXml() { //使用org.springframework.core.io.ClassPathResource,各种环境都能读取resources下的文件。(通用) Resource resource = new ClassPathResource("dome.xml"); Document document = null; try { InputStream inputStream = resource.getInputStream(); SAXReader saxReader = new SAXReader(); //Document 定义了XML文档 document = saxReader.read(inputStream); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } //Element定义XML 元素 Element rootElement = document.getRootElement(); // 这样也可以 //List elements = rootElement.elements(); Iterator iterator = rootElement.elementIterator(); while (iterator.hasNext()) { Element element = (Element) iterator.next(); //Attribute定义了XML的属性 List<Attribute> attributes = element.attributes(); System.out.println("----------获取属性值--------------"); for(Attribute attribute : attributes) { System.out.println(attribute.getValue()); } System.out.println("----------遍历子节点--------------"); Iterator iterator1 = element.elementIterator(); while (iterator1.hasNext()) { Element element1 = (Element) iterator1.next(); System.out.println("节点名:" + element1.getName() + "---节点值:" + element1.getStringValue()); } }}
来源:https://www.cnblogs.com/ggah/p/12168340.html