使用java

时间:2016-07-26 12:55:28

标签: java xml

我正在使用SAX解析xml文件,并将内容传递给execute函数,我通过传递每个子节点及其字段来应用一些验证。我的问题是,根据我的代码,我可以如何为每个子项添加一个带有值的新字段?有关如何操作的任何帮助?

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

    }

0 个答案:

没有答案