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");    
            }

    }
1
  • According to this answer, all you need is an XMLFilterImpl and a Transformer. Commented Jul 26, 2016 at 13:17

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.