2014-06-09 8 views
4

startElement 함수의 XML 파일에서 SAX 처리기의 재정의 기능을 사용하여 요소의 내용을 가져올 수 있습니까?startElement에서 SAX 파서를 사용하여 XML에서 요소의 값을 얻는 방법은 무엇입니까?

다음은 사양입니다.

1) XML 파일

<employees> 
    <employee id="111"> 
     <firstName>Rakesh</firstName> 
     <lastName>Mishra</lastName> 
     <location>Bangalore</location> 
    </employee> 
    <employee id="112"> 
     <firstName>John</firstName> 
     <lastName>Davis</lastName> 
     <location>Chennai</location> 
    </employee> 
    <employee id="113"> 
     <firstName>Rajesh</firstName> 
     <lastName>Sharma</lastName> 
     <location>Pune</location> 
    </employee> 
</employees> 

2) startElement 기능

@Override 
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { 
    .......code in here.......... 
} 

3) 예상 결과

element name : employee 
attribute name : id 
attribute value: 111 
firstName  : Rakesh 
lastName  : Mishra 
location  : Bangalore 

element name : employee 
attribute name : id 
attribute value: 112 
firstName  : John 
lastName  : Davis 
location  : Chennai 

element name : employee 
attribute name : id 
attribute value: 113 
firstName  : Rajesh 
lastName  : Sharma 
location  : Pune 
+0

http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/ –

+0

@PawanAryan, 감사 : 나는 당신이 시작 도움이되기를 바랍니다 . 나는 이미 이것을 확인한다. startElement 함수에 코드 만 쓰고 싶다면 가능합니까? – sakura

+2

* startElement *에서만 속성을 가져옵니다. * 문자 *로 얻는 모든 텍스트 값. 요소를 시작할 때 startElement를 사용하여 * detect *를 사용해야합니다. 그 안에 * 문자 * 방법으로 확인할 수있는 플래그를 설정할 수 있습니다. * 문자 * 안에있는 현재 요소를 알면 그 값을 얻을 수 있습니다. * endElement *에서 해당 플래그를 재설정해야합니다. – helderdarocha

답변

8

이름이이고 startElementendElement이 될 수 있습니다. 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); 
     } 
    } 
} 
+0

실례합니다 !!! 이 옵션은 어떻습니까? tagName 등을 알지 못해도 tagName, attName, attValue 및 tagValue를 한 번에 가져 오려고합니다. 가능한가? – sakura

+0

위와 같이'startElement' 메쏘드에서 태그 이름 ('qName')과'atts' 변수 ('atts.getQName (i)'와'atts.getValue (i))'), 태그의 텍스트 값을 읽으려면'characters' 메쏘드를 사용하고 위에 보이는 것처럼 플래그를 사용해야합니다. 위의 예제를 실행하면 예상 한 결과를 얻어야합니다. – helderdarocha

+0

다른 XML 파일은 어떻습니까? 다른 코드를 구현해야합니까? 주의 할 점으로, 귀하의 코드는 조건에 특정 tagName을 사용합니다. 우리가 구체적인 것을 모른다면 우리는 무엇을해야합니까? – sakura