在指定位置插入节点:

public static String InsertXMLNode(String xmlDoc){
  Document doc = null;
  try {
   doc = DocumentHelper.parseText(xmlDoc); // 将字符串转为XML
   Element rootElt = doc.getRootElement(); // 获取根节点
   Element query = rootElt.element("QueryCondition");
   List list = query.elements();
      String jyjgbh=getProperty().getProperty("jyjgbh");

       //创建一个新节点    
      Element element = DocumentHelper.createElement("jyjgbh");
      element.setText(jyjgbh);

      //在索引为3的位置插入新创建的节点    
      list.add(3,element);
      return doc.asXML();
   
  } catch (Exception e) {
   e.printStackTrace();
   return xmlDoc;
  }
 }

原始xml为:

<?xml version='1.0' encoding='GBK'?>
    <root>
       <QueryCondition>
          <hphm>%E8%B4%B5B88889</hphm>
          <hpzl>01</hpzl>
          <clsbdh>0004</clsbdh>
       </QueryCondition>
    </root>

输入xml为:

 <?xml version="1.0" encoding="GBK"?>
<root><QueryCondition><hphm>%E8%B4%B5B88889</hphm><hpzl>01</hpzl><clsbdh>0004</clsbdh><jyjgbh>125135161</jyjgbh></QueryCondition></root>

替换节点名称和内容,代码如下:

public static String capturePicture(String xmlDoc){
  Document doc = null;
  try {
   doc = DocumentHelper.parseText(xmlDoc); // 将字符串转为XML
   Element rootElt = doc.getRootElement(); // 获取根节点
   Element query = rootElt.element("vehispara");
   List list = query.elements();
   String zpCode=getProperty().getProperty("zpCode");
   Iterator iterator=list.iterator();
   while (iterator.hasNext()) {
    Element  elt = (Element ) iterator.next();
    if(elt.getName().equals("gwjysbbh")){
     elt.setName("zpzl");
     elt.setText(zpCode);
    }
    if(elt.getName().equals("jssj")){
     elt.setName("pzcfsj");
    }
    
   }
      return doc.asXML();
   
  } catch (Exception e) {
   e.printStackTrace();
   return xmlDoc;
  }
 }

原始xml为:

<?xml version='1.0' encoding='GBK'?>
    <root>
       <vehispara>
          <jylsh>%E8%B4%B5B88889</jylsh>
          <jyjgbh>01</jyjgbh>
          <jcxdh>0004</jcxdh>
          <jycs>%E8%B4%B5B88889</jycs>
          <jyxm>01</jyxm>
          <hpzl>0004</hpzl>
          <hphm>%E8%B4%B5B88889</hphm>
          <clsbdh>01</clsbdh>
          <gwjysbbh>0004</gwjysbbh>
          <jssj>0004</jssj>
       </vehispara>
    </root>

输入xml为:

<?xml version="1.0" encoding="GBK"?>
<root><vehispara><jylsh>%E8%B4%B5B88889</jylsh><jyjgbh>01</jyjgbh><jcxdh>0004</jcxdh><jycs>%E8%B4%B5B88889</jycs><jyxm>01</jyxm><hpzl>0004</hpzl><hphm>%E8%B4%B5B88889</hphm><clsbdh>01</clsbdh><zpzl>1234</zpzl><pzcfsj>0004</pzcfsj></vehispara></root>


注意:本文归作者所有,未经作者允许,不得转载