이름이이고 startElement
및 endElement
이 될 수 있습니다. startElement
에 속성을 추가로 가져올 수도 있습니다. characters
에 들어가야하는 가치. 간단한 예를 들어이있는 경우
public class YourHandler extends DefaultHandler {
boolean inFirstNameElement = false;
public class startElement(....) {
if(qName.equals("firstName") {
inFirstNameElement = true;
}
}
public class endElement(....) {
if(qName.equals("firstName") {
inFirstNameElement = false;
}
}
public class characters(....) {
if(inFirstNameElement) {
// do something with the characters in the <firstName> element
}
}
}
는, 각 태그에 대한 부울 플래그를 설정하면 OK입니다 : 여기
는
ContentHandler
사용하여 요소의 값을 얻는 방법에
매우 기본적인 예를이다. 좀 더 복잡한 시나리오가있는 경우 요소 이름을 키로 사용하여지도에 플래그를 저장하거나 XML에 매핑 된 하나 이상의
Employee
클래스를 만들고
<employee>
이 발견 될 때마다 해당 인스턴스를 인스턴스화하고 속성을 채 웁니다. 컬렉션에
endElement
에 추가하십시오.
여기 예제 파일과 함께 작동하는 완전한 ContentHandler
예제가 있습니다.
이
public class SimpleHandler extends DefaultHandler {
class Employee {
public String firstName;
public String lastName;
public String location;
public Map<String, String> attributes = new HashMap<>();
}
boolean isFirstName, isLastName, isLocation;
Employee currentEmployee;
List<Employee> employees = new ArrayList<>();
@Override
public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException {
if(qName.equals("employee")) {
currentEmployee = new Employee();
for(int i = 0; i < atts.getLength(); i++) {
currentEmployee.attributes.put(atts.getQName(i),atts.getValue(i));
}
}
if(qName.equals("firstName")) { isFirstName = true; }
if(qName.equals("lastName")) { isLastName = true; }
if(qName.equals("location")) { isLocation = true; }
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(qName.equals("employee")) {
employees.add(currentEmployee);
currentEmployee = null;
}
if(qName.equals("firstName")) { isFirstName = false; }
if(qName.equals("lastName")) { isLastName = false; }
if(qName.equals("location")) { isLocation = false; }
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (isFirstName) {
currentEmployee.firstName = new String(ch, start, length);
}
if (isLastName) {
currentEmployee.lastName = new String(ch, start, length);
}
if (isLocation) {
currentEmployee.location = new String(ch, start, length);
}
}
@Override
public void endDocument() throws SAXException {
for(Employee e: employees) {
System.out.println("Employee ID: " + e.attributes.get("id"));
System.out.println(" First Name: " + e.firstName);
System.out.println(" Last Name: " + e.lastName);
System.out.println(" Location: " + e.location);
}
}
}
http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/ –
@PawanAryan, 감사 : 나는 당신이 시작 도움이되기를 바랍니다 . 나는 이미 이것을 확인한다. startElement 함수에 코드 만 쓰고 싶다면 가능합니까? – sakura
* startElement *에서만 속성을 가져옵니다. * 문자 *로 얻는 모든 텍스트 값. 요소를 시작할 때 startElement를 사용하여 * detect *를 사용해야합니다. 그 안에 * 문자 * 방법으로 확인할 수있는 플래그를 설정할 수 있습니다. * 문자 * 안에있는 현재 요소를 알면 그 값을 얻을 수 있습니다. * endElement *에서 해당 플래그를 재설정해야합니다. – helderdarocha