我必须解析 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;
}