Xml Parse编辑在Java中保存和创建

时间:2013-08-08 18:19:43

标签: java xml dom xml-parsing dom4j

我必须解析XML,因为现在我已经使用了SAX解析器,我现在必须显示,编辑它,最后创建XML,现在问题是如何使用SAX Parser,因为它没有该功能。我处境艰难,我也搜索过有关dom4j和DOM的事情。我的代码如下所示。

public class XmlBack extends DefaultHandler {

    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {        
        if (qName.equalsIgnoreCase("VarGroup")) {
            varGroupVariables = new HashMap<String, List<VarGroupVariable>>();
        }else if (qName.equalsIgnoreCase("Variable")) {
            varGroupVariable = new VarGroupVariable();
            nameAttribute = attributes.getValue("Name");
            varGroupVariable.setName(nameAttribute);
        }else if (qName.equalsIgnoreCase("TYP")) {
            btype = true;
        }else if (qName.equalsIgnoreCase("VALUE")) {
            bvalue = true;
        }       
    }
    public void characters(char ch[], int start, int length)
            throws SAXException {
        String vtype = null;

        if (btype) {
            vtype = new String(ch, start, length);
            varGroupVariable.setType(vtype);
            btype = false;
        }

        Double value = null;
        if (bvalue) {
            String vvalue = new String(ch, start, length);
            try {
                value = Double.valueOf(vvalue);
            } catch (NumberFormatException ne) {
                value = 0d;
            }
            varGroupVariable.setValue(value);
            bvalue = false;
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if (qName.equalsIgnoreCase("Variable")) {
            String varGroupVariableName = varGroupVariable.getName().split("\\.")[0];
            String name = varGroupVariableName.substring(0,varGroupVariableName.length() - 1);
            String name1= varGroupVariableName = varGroupVariable.getName().split("\\.")[1];
            System.out.println(name1);
            List<VarGroupVariable> varGroupVariablesList;
            if(varGroupVariables.containsKey(name)) {
                varGroupVariablesList = varGroupVariables.get(name);                 
            }else {
                varGroupVariablesList = new ArrayList<VarGroupVariable>();
            }
            int serial = varGroupVariablesList.size();
            varGroupVariable.setSerial(++serial);
            varGroupVariablesList.add(varGroupVariable);        
            varGroupVariables.put(name, varGroupVariablesList);
            //System.out.println(name+"\n");
            }
    }
    private int no = 1;
    boolean bcore,bmold,bvalue,btype = false;
    String nameAttribute;
    Map<String, List<VarGroupVariable>> varGroupVariables;
    VarGroupVariable varGroupVariable;
}

1 个答案:

答案 0 :(得分:1)

除非您的XML不是非常复杂,或者您有可用的架构,否则最简单的选择可能是JAXB。有几个教程,例如this。当然,StackOverflow也是JAXB知识的良好来源。