구문 분석기가 실패했는지 여부를 확인할 수있는 데이터 구조를 사용합니다. 예 : 응답이 거짓인지 아닌지
public class XMLResponse {
private boolean hasFailed;
private Employee employee;
public void setFailure(boolean in) {
this.hasFailed=in;
}
public void setEmployee(Employee in) {
this.employee=in;
}
}
그리고 당신의 파서
를 참조하십시오. 이는 성공했을 경우 웹 서비스의 응답에 응답 태그가 포함되지 않는다는 사실에 기반합니다.
파서의 예입니다. 사용하기 전에 몇 가지 조작이 필요할 수 있습니다. 응답에 1 명의 직원 만 얻는 경우에만 유용합니다. 그렇지 않으면 목록을 사용해야합니다.
public class XMLHandler extends DefaultHandler {
private XMLResponse myResponse;
private Employee employee;
public XMLResponse getParsedData() {
return this.myResponse;
}
@Override
public void startDocument() throws SAXException {
myResponse = new XMLResponse();
employee = new Employee();
}
@Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
buffer = new StringBuffer();
if(localName.equals("employee")) {
employee.setId(atts.getValue("id"));
}
}
@Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if(localName.equals("response")) {
if(buffer.toString().contains("failure")) {
myResponse.setFailure(true);
}
}
else if(localName.equals("info")) {
/*
* This is only an example, could bee employee or whatever. You should use the startElement to get the tag.
*/
}
else if(localName.equals("name")) {
employee.setName(buffer.toString());
}
else if(localName.equals("age")) {
employee.setAge(buffer.toString());
}
else if(localName.equals("employee")) {
myResponse.setEmployee(employee);
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
StringBuffer buffer;
@Override
public void characters(char ch[], int start, int length) {
buffer.append(ch,start,length);
}
왜 파서를 하나만 사용합니까? 오류 파서가 null 또는 오류에 대해 알려주는 일종의 플래그를 반환하도록하십시오. –
David Olsson 단일 구문 분석기를 사용할 수 있습니다. 하지만 나는 어떻게 서로 다른 XML에 대해 단일 파서를 사용할 수 있는지에 대해 잘 모른다. 정보를 입력하십시오. –
예를 들어 하나의 파서를 사용할 수있는 답변을 게시했습니다. –