1

I'm parsing an xml file using SAX, and passing the content into execute function, where I'm applying some validation by passing on each child and its fields. My question is how, based on my code, can I add a new field with a value to each subchild ? Any help on how to do so?

    <?xml version="1.0" encoding="iso-8859-1" standalone="yes"?> 
<DOCUMENTS type="tst">
  <DOCUMENT>
    <CODE>123456</CODE>
    <NBR>6</NBR>
  </DOCUMENT>
  <DOCUMENT>
    <CODE>987654</CODE>
    <NBR>1</NBR>
  </DOCUMENT>
</DOCUMENTS>

    private Document convertXmlFileToDocument(String path){

        SAXBuilder sb=new SAXBuilder();
        File xmlFile = new File(path);
        Document doc = null;
        try {
            doc = sb.build(xmlFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return doc;
    }

   public void execute() throws Exception {

        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 = "";
            String fileNameValue = "";
            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;
                            }
                        }
                    }


                }else{
                    break;
                }
            }

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

    }
cdomination
  • 605
  • 1
  • 7
  • 25
mikeb
  • 709
  • 2
  • 9
  • 35
  • According to [this](http://stackoverflow.com/a/13688837/187808) answer, all you need is an `XMLFilterImpl` and a `Transformer`. – Tamas Rev Jul 26 '16 at 13:17

0 Answers0