dom4j创建xml报文并生成

我使用的是dom4j创建xml报文

1.创建root节点
         Document document = DocumentHelper.createDocument();  
         Element root = DocumentHelper.createElement("RBSPMessage");  
         document.setRootElement(root); 

2.在root节点下添加节点
         Element Version = root.addElement("Version");
         Element SenderIDElement = root.addElement("SenderID");

3.为节点添加值

         SenderIDElement.setText("C00-10002029");
4.为节点添加属性值
         Element Security = root.addElement("Security");
         Element Signature = Security.addElement("Signature");
         Signature.addAttribute("Algorithm","des");
5.生成xml报文
         OutputFormat format = OutputFormat.createCompactFormat();
          format.setEncoding("UTF-8");
          StringWriter writer = new StringWriter();
          XMLWriter output = new XMLWriter(writer, format);
          output.write(document);
          writer.close();
          output.close();
          return writer.toString();

6.返回报文后,获取某某节点有几个节点。

          Document document = DocumentHelper.parseText(xml);
          Element rootElement = document.getRootElement();
          List list =rootElement.selectNodes("/RBSPMessage/Method/Items/Item/Value/Row");
          result = String.valueOf(list.size());

posted @ 2018-09-19 13:44  闭眼的鱼  阅读(1765)  评论(0编辑  收藏  举报