0

我必须解析 XML 到目前为止我已经使用了 SAX 解析器现在我必须显示、编辑它并最终创建 XML 现在的问题是我如何使用 SAX 解析器来做到这一点,因为它没有那个功能。我处境艰难,我也搜索过有关 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;
}
4

1 回答 1

1

除非您的 XML 不是非常复杂,或者如果您有可用的模式)最简单的选择可能是 JAXB。周围有几个教程,例如 this。当然,StackOverflow 也是一个很好的 JAXB 知识来源。

于 2013-08-09T13:43:17.727 回答