.
이것은 이벤트 지향적 인 XML 파일 구문 분석 방법으로, 구문 분석 중에 대상 파일에 직접 쓰고 싶을 때 좋은 방법 일 수 있습니다. SAX Parser는 전체 XML 컨텐트를 메모리로 읽지 않지만 입력 스트림의 요소를 enconters 할 때 메서드를 트리거합니다. 지금까지 내가 경험 한대로 이것은 매우 기억에 효율적인 처리 방법이다.
SAX는 Stax-Solution과 비교하여 데이터를 애플리케이션에 '푸시 (push)'합니다. 즉, 상태를 유지해야한다는 것입니다 (즉, 어떤 태그가 사용자와 같은지). 따라서 현재 상태를 추적해야합니다 위치.
import java.io.FileReader;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
public class SaxExample implements ContentHandler
{
private String currentValue;
public static void main(final String[] args) throws Exception
{
final XMLReader xmlReader = XMLReaderFactory.createXMLReader();
final FileReader reader = new FileReader("datasource.xml");
final InputSource inputSource = new InputSource(reader);
xmlReader.setContentHandler(new SaxExample());
xmlReader.parse(inputSource);
}
@Override
public void characters(final char[] ch, final int start, final int length) throws SAXException
{
currentValue = new String(ch, start, length);
}
@Override
public void startElement(final String uri, final String localName, final String qName, final Attributes atts) throws SAXException
{
// react on the beginning of tag "GroupBMsg" <GroupBMSg>
if (localName.equals("GroupBMsg"))
{
currentValue="";
}
}
@Override
public void endElement(final String uri, final String localName, final String qName) throws SAXException
{
// react on the ending of tag "GroupBMsg" </GroupBMSg>
if (localName.equals("GroupBMsg"))
{
// TODO: write into file
System.out.println(currentValue);
}
}
// the rest is boilerplate code for sax
@Override
public void endDocument() throws SAXException {}
@Override
public void endPrefixMapping(final String prefix) throws SAXException {}
@Override
public void ignorableWhitespace(final char[] ch, final int start, final int length)
throws SAXException {}
@Override
public void processingInstruction(final String target, final String data)
throws SAXException {}
@Override
public void setDocumentLocator(final Locator locator) { }
@Override
public void skippedEntity(final String name) throws SAXException {}
@Override
public void startDocument() throws SAXException {}
@Override
public void startPrefixMapping(final String prefix, final String uri)
throws SAXException {}
}
특정 언어 당신은 '이 : 그건 당신이 정말
다음 예는 당신의 구조 xml 파일에 읽고 GroupBMsg-태그 내의 모든 텍스트를 출력 필요 뭔가 있는지 확실하지 않습니다 다시 사용할거야? –
파일의 구조를 확인해야합니까, 아니면 sé 당 유효하다고 생각할 수 있습니까? – Thilo
JAXB/Spring Batch를 사용하고 있습니다. 많은 게시물을 읽었지만 xml보다 효과적으로 처리하는 방법에 대해서는 아직 모릅니다. – Weber