2016-07-25 48 views
0
I have an xml file that I'm parsing using json (function:convertXmlFileToDocument), then I'm getting xml validation rules from the database (function: getRulesByType). 

我正在做两个for循环来测试xml文件中的每个元素是否满足验证条件,比如强制。 现在,如果验证在被验证的xml文件上是正确的,我需要添加一个在根下有效的元素。我试过这种方法: /Document.appendChild(xmlDoc.createElement(“status”)); Document.setContent(“valid”);/ 但没有成功。任何帮助如何做到这一点?在java的根目录下添加一个元素

公共无效的execute()抛出异常{

try{ 

    Document xmlDoc = convertXmlFileToDocument("c:\\TEST.xml"); 

    String xmlType = xmlDoc.getRootElement().getAttributeValue("type"); 
    HashMap<String, HashMap<String, String>> hashValidationRules = getRulesByType(xmlType); 

    HashMap<String, String> hashValidationRulesAtt = null; 
    List<Element> childElem = xmlDoc.getRootElement().getChildren(); 
    List<Element> subChildElem = null; 
    String elemName = ""; 
    String elemValue = ""; 
    boolean allIsOk = true; 
    for (int j = 0; j < childElem.size(); j++) { 

     subChildElem = childElem.get(j).getChildren(); 

     if(allIsOk){ 
      for (int j2 = 0; j2 < subChildElem.size(); j2++) { 
       elemName = subChildElem.get(j2).getName(); 
       elemValue = subChildElem.get(j2).getValue(); 

       if(hashValidationRules.containsKey(elemName)){ 
        hashValidationRulesAtt = hashValidationRules.get(elemName); 
        if(hashValidationRulesAtt.get("mandatory").equals("true") && (elemValue==null||elemValue.equals(""))){ 
         allIsOk = false; 
         break; 
        } 
        if(elemValue.length()> Integer.parseInt(hashValidationRulesAtt.get("size"))){ 
         allIsOk = false; 
         break; 
        } 
        if(hashValidationRulesAtt.get("format").equals("numeric")){ 
         try { 
          Integer.parseInt(elemValue); 
         } catch (Exception e) { 
          allIsOk = false; 
          break; 
         } 
        } 
        if(hashValidationRulesAtt.get("format").equals("float")){ 
         try { 
          Float.parseFloat(elemValue); 
         } catch (Exception e) { 
          allIsOk = false; 
          break; 
         } 
        } 
       } 
      } 
     }else{ 
      /*Document.appendChild(xmlDoc.createElement("status")); 
      Document.setContent("valid");*/ 
      break; 
     } 
    } 

    if(!allIsOk){ 
     System.out.println("\n\n ****Error**** \n\n");  
    } 

} 
finally { 
    _Reader.endRead(); 
} 

}

回答

0

下面将帮助,你可以得到的第一个子元素追加到它。

Document existingDocument = builder.parse(is); 
Element statusOfTheDocument = existingDocument.createElement("status"); 
statusOfTheDocument.setTextContent("valid"); 
existingDocument.getFirstChild().appendChild(statusOfTheDocument);