我有一个java文件,它使用SAX解析XML文件,似乎工作得很好。
以下是我的SAX.java文件:
public class SAX extends DefaultHandler{
private final List<Student> studentList = new ArrayList<Student>();
private String tempVal;
private Student tempStudent;
public void runExample(){
parseDocument();
outputList();
}
private void parseDocument(){
try {
// get a factory object
SAXParserFactory spf = SAXParserFactory.newInstance();
// get an instance of the parser
SAXParser sp = spf.newSAXParser();
// parse the XML file and register this
// class for callbacks
sp.parse("Students.xml", this);
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void outputList(){
for(Student student : studentList){
System.out.println(student);
}
}
// the event handlers....
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// reset
tempVal = "";
if(qName.equalsIgnoreCase("Student")){
// create a new Employee object
tempStudent = new Student();
tempStudent.setTitle(attributes.getValue("Title"));
}
// System.out.println(
// "startElement::qName is "+qName);
}
@Override
public void characters(char []ch, int start, int length) throws SAXException{
tempVal = new String(ch, start, length);
// System.out.println("tempVal is "+tempVal);
}
@Override
public void endElement(String uri, String localname, String qName) throws SAXException {
if(qName.equalsIgnoreCase("Student")){
studentList.add(tempStudent);
} else if(qName.equalsIgnoreCase("Name")){
tempStudent.setName(tempVal);
} else if(qName.equalsIgnoreCase("Age")){
tempStudent.setAge(Integer.parseInt(tempVal));
} else if(qName.equalsIgnoreCase("College")){
tempStudent.setCollege(tempVal);
} else if(qName.equalsIgnoreCase("School")) {
tempStudent.setSchool(tempVal);
}
}
public static void main(String []args){
SAX spe = new SAX();
spe.runExample();
}
}但是,我被要求在图形用户界面中展示这一点。当单击特定的单选按钮并单击parse时,将使用SAX解析XML文件,并在文本框中显示结果。我已经得到了GUI,它已经编码了,我的问题是我对GUI的知识有限,我不知道如何将两者集成在一起。
public void actionPerformed(ActionEvent e) {
else if (e.getSource() == parseButton){
if(saxRadioButton.isSelected()){
// do SAX stuff
}我只是想找个人给我指个方向。我应该单独生成SAX文件,还是应该直接放入If语句中。我完全迷路了。
发布于 2016-03-27 04:59:58
从SAX类中获取解析后的XML,然后将其设置为所需的组件。将gui从你的进程中分离出来是有意义的,并且会更容易调试。例如:
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(parseButton)){
if(saxRadioButton.isSelected()) {
String result = SAX.yourParsingHere();
yourTextArea.setText(result);
}
}
}https://stackoverflow.com/questions/36240693
复制相似问题