XMLStreamReader 클래스의 next 메서드는 이벤트를 반환하고, 반환된 이벤트에 따라 맞는 처리를 하게 된다.


StAX의 XMLEvent 클래스에는 XML의 이벤트가 상수로 정의되어 있는데, 아래와 같다.

  • XMLEvent.START_ELEMENT
  • XMLEvent.END_ELEMENT
  • XMLEvent.PROCESSING_INSTRUCTION
  • XMLEvent.CHARACTERS
  • XMLEvent.COMMENT
  • XMLEvent.SPACE
  • XMLEvent.START_DOCUMENT
  • XMLEvent.END_DOCUMENT
  • XMLEvent.ENTITY_REFERENCE
  • XMLEvent.ATTRIBUTE
  • XMLEvent.DTD
  • XMLEvent.CDATA
  • XMLEvent.NAMESPACE
  • XMLEvent.NOTATION_DECLARATION
  • XMLEvent.ENTITY_DECLARATION
참고로 이는 XMLStreamConstants에 동일하게 정의되어 있다.

또한 각각의 이벤트에 따라 사용할 수 있는 메서드가 정해져있는데,
이벤트에 맞지 않는 메서드를 사용하면 예외가 발생한다.

 이벤트

유효한 메서드 
 모든 이벤트에 적용가능

 getProperty(), hasNext(), require(), close(), getNamespaceURI(),
 isStartElement(), isEndElement(), isCharacters(),isWhiteSpace(), 

 getNamespaceContext(), getEventType(),getLocation(), hasText(), 

 hasName()

 START_ELEMENT

 next(), getName(), getLocalName(), hasName(), getPrefix(), 

 getAttributeXXX(), isAttributeSpecified(),getNamespaceXXX(), 

 getElementText(), nextTag()

 ATTRIBUTE  next(), nextTag() getAttributeXXX(), isAttributeSpecified()
 NAMESPACE  next(), nextTag() getNamespaceXXX()

 END_ELEMENT

 next(), getName(), getLocalName(), hasName(), getPrefix(), 

 getNamespaceXXX(), nextTag()

 CHARACTERS  next(), getTextXXX(), nextTag()
 CDATA  next(), getTextXXX(), nextTag()
 COMMENT  next(), getTextXXX(), nextTag()
 SPACE  next(), getTextXXX(), nextTag()
 START_DOCUMENT  next(), getEncoding(), getVersion(), isStandalone(), standaloneSet(),
 getCharacterEncodingScheme(), nextTag()

 END_DOCUMENT

 close()
 PROCESSING_INSTRUCTION  next(), getPITarget(), getPIData(), nextTag()
 ENTITY_REFERENCE  next(), getLocalName(), getText(), nextTag()
 DTD  next(), getText(), nextTag()



http://tutorials.jenkov.com/java-xml/stax-xmlstreamwriter.html에서 가져옴


The XMLStreamWriter class in the Java StAX API allows you to write XML events (elements, attributes etc.) either to a Writer, an OutputStream, or a Result (special JAXP object).

Here is a simple example that writes a series of events to disk, using a FileWriter:

XMLOutputFactory factory      = XMLOutputFactory.newInstance();

 try {
     XMLStreamWriter writer = factory.createXMLStreamWriter(
             new FileWriter("data\\output2.xml"));

     writer.writeStartDocument();
     writer.writeStartElement("document");
     writer.writeStartElement("data");
     writer.writeAttribute("name", "value");
     writer.writeEndElement();
     writer.writeEndElement();
     writer.writeEndDocument();

     writer.flush();
     writer.close();

 } catch (XMLStreamException e) {
     e.printStackTrace();
 } catch (IOException e) {
     e.printStackTrace();
 }

The result of executing this code is the following XML file (line breaks inserted for readability):

<?xml version='1.0' encoding='utf-8'?>
<document><data name="value"></data></document>

'밤을 지새다 > Java' 카테고리의 다른 글

Java PriorityQueue  (0) 2012.05.07
Java StAX Event  (0) 2012.05.01
Java StAX: XMLStreamReader - The Cursor API  (0) 2012.04.30
Java StAX: XMLEventWriter - The Iterator Writer API  (0) 2012.04.30
Java StAX: XMLEventReader - The Iterator API  (0) 2012.04.30

http://tutorials.jenkov.com/java-xml/stax-xmlstreamreader.html에서 가져옴


The XMLStreamReader class in Java StAX provides a Cursor style API for parsing XML. Like theIterator API it allows you to move from event to event in the XML, letting you control when to move to the next event. An "event" in this case is for instance the beginning of an element, the end of an element, a group of text etc. In other words, pretty much the same events you would get from a SAX parser.

To read more about the difference between the Iterator and Cursor style API's, read the introduction to StAX: Java StAX Parser

You create an XMLStreamReader via the javax.xml.stream.XMLInputFactory class. Here is how that looks:

XMLInputFactory factory = XMLInputFactory.newInstance();

//get Reader connected to XML input from somewhere..
Reader reader = getXmlReader();

try {

    XMLStreamReader streamReader =
        factory.createXMLStreamReader(reader);
    
} catch (XMLStreamException e) {
    e.printStackTrace();
}

Once created you can iterate through the XML input from the underlying Reader. Here is how that looks:

XMLStreamReader streamReader = factory.createXMLStreamReader(
    new FileReader("data\\test.xml"));

while(streamReader.hasNext()){
    streamReader.next();
    if(streamReader.getEventType() == XMLStreamReader.START_ELEMENT){
        System.out.println(streamReader.getLocalName());
    }
}

You obtain the event type by calling the XMLStreamReader.getEventType() method. When you know the event type, you can process the given event as you need.


XML Stream Events

Below is a list of the events you can encounter in an XML stream. There are constants for each of these events in the javax.xml.stream.XMLStreamConstants interface.

  • ATTRIBUTE
  • CDATA
  • CHARACTERS
  • COMMENT
  • DTD
  • END_DOCUMENT
  • END_ELEMENT
  • ENTITY_DECLARATION
  • ENTITY_REFERENCE
  • NAMESPACE
  • NOTATION_DECLARATION
  • PROCESSING_INSTRUCTION
  • SPACE
  • START_DOCUMENT
  • START_ELEMENT

XML Event Processing

From the XMLStreamReader you can get access to the corresponding XML data. You can also get information about where (line number + column number) in the XML stream the event was encountered.

http://tutorials.jenkov.com/java-xml/stax-xmleventwriter.html에서 가져옴


The XMLEventWriter class in the Java StAX API allows you to write StAX XMLEvent's either to aWriter, an OutputStream, or a Result (special JAXP object).

Here is a simple example that writes a series of events to disk, using a FileWriter:

XMLOutputFactory factory      = XMLOutputFactory.newInstance();
XMLEventFactory  eventFactory = XMLEventFactory.newInstance();

try {
    XMLEventWriter writer =
            factory.createXMLEventWriter(
                    new FileWriter("data\\output.xml"));

    XMLEvent event = eventFactory.createStartDocument();
    writer.add(event);

    event = eventFactory.createStartElement(
            "jenkov", "http://jenkov.com", "document");
    writer.add(event);

    event = eventFactory.createNamespace(
            "jenkov", "http://jenkov.com");
    writer.add(event);

    event = eventFactory.createAttribute
            ("attribute", "value");
    writer.add(event);

    event = eventFactory.createEndElement(
            "jenkov", "http://jenkov.com", "document");
    writer.add(event);

    writer.flush();
    writer.close();
} catch (XMLStreamException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

The result of executing this code is the following XML file (line breaks inserted for readability):

<?xml version='1.0' encoding='UTF-8'?>
<jenkov:document xmlns:jenkov="http://jenkov.com" attribute="value">
</jenkov:document>

As you can see, it is possible to generate XML using XMLEvent's and the XMLEventWriter. But, if you are looking to just output some quick XML, you might be better off using the XMLStreamWriterinstead. It's API is easier to work with, and results in more dense code.


Chaining XMLEventReader and XMLEventWriter

It is possible to add the XMLEvent's available from an XMLEventReader directly to an XMLEventWriter. In other words, you are pooring the XML events from the reader directly into the writer. You do so using the XMLEventWriter.add(XMLEventReader) method.

http://tutorials.jenkov.com/java-xml/stax-xmleventreader.html에서 가져옴


The XMLEventReader class in Java StAX provides an Iterator style API for parsing XML. In other words, it allows you to move from event to event in the XML, letting you control when to move to the next event. An "event" in this case is for instance the beginning of an element, the end of an element, a group of text etc. In other words, pretty much the same events you would get from a SAX parser.

You create an XMLEventReader via the javax.xml.stream.XMLInputFactory class. Here is how that looks:

XMLInputFactory factory = XMLInputFactory.newInstance();

//get Reader connected to XML input from somewhere..
Reader reader = getXmlReader();

try {

    XMLEventReader eventReader =
        factory.createXMLEventReader(reader);
    
} catch (XMLStreamException e) {
    e.printStackTrace();
}

Once created you can iterate through the XML input from the underlying Reader. Here is how that looks:

while(eventReader.hasNext()){

    XMLEvent event = eventReader.nextEvent();

    if(event.getEventType() == XMLStreamConstants.START_ELEMENT){
        StartElement startElement = event.asStartElement();
        System.out.println(startElement.getName().getLocalPart());
    }
    //handle more event types here...
}

You obtain an XMLEvent object from the XMLStreamReader by calling its nextEvent() method. From the event object you can check what type of event you've got, by calling its getEventType() method. Depending on what type of event you have encountered, you will do different actions.


XML Stream Events

Below is a list of the events you can encounter in an XML stream. There are constants for each of these events in the javax.xml.stream.XMLStreamConstants interface.

  • ATTRIBUTE
  • CDATA
  • CHARACTERS
  • COMMENT
  • DTD
  • END_DOCUMENT
  • END_ELEMENT
  • ENTITY_DECLARATION
  • ENTITY_REFERENCE
  • NAMESPACE
  • NOTATION_DECLARATION
  • PROCESSING_INSTRUCTION
  • SPACE
  • START_DOCUMENT
  • START_ELEMENT

XMLEvent Processing

From the XMLEvent object you can get access to the corresponding XML data. You can also get information about where (line number + column number) in the XML stream the event was encountered.

You can turn the event object into a more specific event type object, by calling one of these 3 methods:

  1. asStartElement()
  2. asEndElement()
  3. asCharacters()

Exactly how that works with events like START_DOCUMENT, NAMESPACE or PROCESSING_INSTRUCTION, I don't yet know. I'll update this text when I do. Luckily, we will most often only need the START_ELEMENT, END_ELEMENT, and CHARACTERS events, so this lack of knowledge isn't crucial.


XMLEvent.asStartElement()

The asStartElement() method returns a java.xml.stream.StartElement object. From this object you can get the name of the element, get the namespaces of the element, and the attributes of the element. See the Java 6 JavaDoc for more detail.


XMLEvent.asEndElement()

The asEndElement() method returns a java.xml.stream.EndElement object. From this object you can get the element name and namespace.


XMLEvent.asCharacters()

The asCharacters() method return a java.xml.stream.Characters object. From this object you can obtain the characters themselves, as well as see if the characters are CDATA, white space, or ignorable white space.

'밤을 지새다 > Java' 카테고리의 다른 글

Java StAX: XMLStreamReader - The Cursor API  (0) 2012.04.30
Java StAX: XMLEventWriter - The Iterator Writer API  (0) 2012.04.30
Java StAX: XMLOutputFactory  (0) 2012.04.30
Java StAX: XMLInputFactory  (0) 2012.04.30
Java StAX  (0) 2012.04.30

http://tutorials.jenkov.com/java-xml/stax-xmloutputfactory.html에서 가져옴


The class javax.xml.stream.XMLOutputFactory is a root component of the Java StAX API. From this class you can create both an XMLStreamWriter and an XMLEventWriter. Here are two examples:

XMLOutputFactory factory = XMLOutputFactory.newInstance();

XMLEventWriter eventWriter =
    factory.createXMLEventWriter(
        new FileWriter("data\\test.xml"));

XMLStreamWriter streamWriter =
    factory.createXMLStreamWriter(
        new FileWriter("data\\test.xml"));

XMLOutputFactory Properties

You can set one property on the XMLOutputFactory instance using the setProperty() method. Here is an example:

factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);

For a full list of properties and their meaning, see the official JavaDoc (in Java 6) for the StAX API.

'밤을 지새다 > Java' 카테고리의 다른 글

Java StAX: XMLEventWriter - The Iterator Writer API  (0) 2012.04.30
Java StAX: XMLEventReader - The Iterator API  (0) 2012.04.30
Java StAX: XMLInputFactory  (0) 2012.04.30
Java StAX  (0) 2012.04.30
Exceptions  (0) 2011.09.05

http://tutorials.jenkov.com/java-xml/stax-xmlinputfactory.html에서 가져옴


The class javax.xml.stream.XMLInputFactory is a root component of the Java StAX API. From this class you can create both an XMLStreamReader and an XMLEventReader. Here are two examples:

XMLInputFactory factory = XMLInputFactory.newInstance();

XMLEventReader eventReader =
    factory.createXMLEventReader(
        new FileReader("data\\test.xml"));

XMLStreamReader streamReader =
    factory.createXMLStreamReader(
        new FileReader("data\\test.xml"));

XMLInputFactory Properties

You can set various properties on the XMLInputFactory instance using the setProperty() method. Here is an example:

factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);

For a full list of properties and their meaning, see the official JavaDoc (in Java 6) for the StAX API.

'밤을 지새다 > Java' 카테고리의 다른 글

Java StAX: XMLEventReader - The Iterator API  (0) 2012.04.30
Java StAX: XMLOutputFactory  (0) 2012.04.30
Java StAX  (0) 2012.04.30
Exceptions  (0) 2011.09.05
자바. 얼마나 알고 사용하고 계신가요?  (0) 2011.08.25

http://tutorials.jenkov.com/java-xml/stax.html에서 가져옴


The StAX Java API for XML processing is designed for parsing XML streams, just like the SAX API's. The main differences between the StAX and SAX API's are:

  • StAX is a "pull" API. SAX is a "push" API.
  • StAX can do both XML reading and writing. SAX can only do XML reading.

It is pretty obvious what the difference between a "read + write" capable API vs. a "read" capable API is. But the difference between a "pull" and a "push" style API is less obvious, so I'll talk a little about that. For a more feature-by-feature type comparison of SAX and StAX, see the text SAX vs. StAX.

NOTE: This text uses SVG (Scalable Vector Graphics) diagrams. If you are using Internet Explorer you will need the Adobe SVG Plugin do display these diagrams. Firefox 3.0.5+ users and Google Chrome users should have no problems.


"Pull" vs. "Push" Style API

SAX is a push style API. This means that the SAX parser iterates through the XML and calls methods on the handler object provided by you. For instance, when the SAX parser encounters the beginning of an XML element, it calls the startElement on your handler object. It "pushes" the information from the XML into your object. Hence the name "push" style API. This is also referred to as an "event driven" API. Your handler object is notified with event-calls when something interesting is found in the XML document ("interesting" = elements, texts, comments etc.).

The SAX parser push style parsing is illustrated here:

StAX is a pull style API. This means that you have to move the StAX parser from item to item in the XML file yourself, just like you do with a standard Iterator or JDBC ResultSet. You can then access the XML information via the StAX parser for each such "item" encountered in the XML file ("item" = elements, texts, comments etc.).

The StAX parser pull style parsing is illustrated here:

In fact, StAX has two different reader API's. One that looks most like using an Iterator and one that looks most like using a ResultSet. These are called the "iterator" and "cursor" readers.

So, what is the difference between these two readers?

The iterator reader returns an XML event object from it's nextEvent() calls. From this event object you can see what type of event you had encountered (element, text, comment etc.). This event element is immutable, and can be parsed around to other parts of your application. You can also hang on to earlier event objects when iterating to the next event. As you can see, this works very much like how you use an ordinary Iterator when iterating over a collection. Here, you are just iterating over XML events. Here's a sketch:

XMLEventReader reader = ...;

while(reader.hasNext()){
    XMLEvent event = reader.nextEvent();

    if(event.getEventType() == XMLEvent.START_ELEMENT){
        StartElement startElement = event.asStartElement();
        System.out.println(startElement.getName().getLocalPart());
    }
    //... more event types handled here...
}

The cursor reader does not return events from it's next() call. Rather this call moves the cursor to the next "event" in the XML. You can then call methods directly on the cursor to obtain more information about the current event. This is very similar to how you iterate the records of a JDBCResultSet, and call methods like getString() or getLong() to get values from the current record pointed to by the ResultSet. Here is a sketch:

XMLStreamReader streamReader = ...;

while(streamReader.hasNext()){
    int eventType = streamReader.next();

    if(eventType == XMLStreamReader.START_ELEMENT){
        System.out.println(streamReader.getLocalName());
    }

    //... more event types handled here...
}

So, one of the main differences is, that you can hang on to earlier XML event objects when using the iterator style API. You cannot do this when using the cursor style API. Once you move the cursor to the next event in the XML stream, you have no information about the previous event. This speaks in favour of using the iterator style API.

However, the cursor style API is said to be more memory-efficient than the iterator style API. So, if your application needs absolute top-performance, use the cursor style API.

Both of these two StAX API's will be covered in more detail in later texts. See the table of contents in the right side of this page.


Java StAX Implementation

At the time of writing (Java 6) only the StAX interfaces are bundled with the JDK. There is no StAX implementation built into Java. But, there is a standard implementation which can be found here:

http://stax.codehaus.org/


기본 표현


  • .    줄바꿈 문자를 제외한 임의의 문자 하나를 대체
  • \    이스케이프 문자
  • []    집합
  • [\b]    역스페이스
  • \f    페이지 넘김(form feed) 문자
  • \n    줄바꿈(line feed) 문자
  • \r    캐리지 리턴
  • \t    탭
  • \v    수직 탭
  • \d    숫자 하나([0-9])와 동일
  • \D    숫자를 제외한 문자([^0-9])와 동일
  • \w    대소문자와 밑줄을 포함하는 모든 영숫자(=[a-zA-Z0-9_])
  • \W    영숫자나, 밑줄이 아닌 모든 문자(=[^a-zA-Z0-9_])
  • \s    모든 공백 문자(=[\f\n\r\t\v])
  • \S    공백 문자가 아닌 모든 문자(=[^\f\n\r\t\v])
  • *    0-n번 반복 (greedy)
  • ?    0-1번 (greedy)
  • +    1-n번 반복 (greedy)
  • *?    0-n번 반복 (lazy)
  • +?    1-n번 반복 (lazy)
  • {숫자}    숫자 만큼 반복
  • {숫자1, 숫자2}    최소 숫자1번 반복하고 숫자2번까지 반복
  • {숫자,}    최소 숫자만큼 반복 (greedy)
  • {숫자,}?    최소 숫자만큼 반복 (lazy)
  • ()    하위 표현식
  • |    OR
  • \숫자    역참조, 숫자는 하위 표현식의 인덱스, 0은 전체.
  • $숫자    치환시의 역참조
  • \E    \L혹은 \U 변환의 끝을 나타냄
  • \l    다음에 오는 글자를 소문자로 치환
  • \L    \E를 만날 때까지 모든 문자를 소문자로 치환
  • \u    다음에 오는 글자를 대문자로 치환
  • \U    \E를 만날 때까지 모든 문자를 대문자로 치환




위치 찾기


  • \b    단어 경계 지정
  • ^표현    문자열 시작 문자 지정
  • $표현    문자열 끝 문자 지정
  • (?m)    줄바꿈문자를 공백문자에 포함되도록 한다.




POSIX


  • [:alnum:]    모든 영숫자([a-zA-Z0-9)
  • [:alpha:]    모든 영문자([a-zA-Z])
  • [:blank:]    빈칸이나 탭 문자와 같음
  • [:cntrl:]    아스키 제어문자(아스키 0-31, 127)
  • [:digit:]    모든 한 자리 숫자([0-9])
  • [:graph:]    [:print:]와 동일하나 빈칸(space)은 제외
  • [:lower:]    모든 소문자([a-z])
  • [:print:]    출력가능한 모든 문자
  • [:punct:]    [:alnum:]이나 [:cntrl:]가 포함되지 않은 모든 문자
  • [:space:]    빈칸을 포함한 모든 공백 문자([\f\n\r\t\v])
  • [:upper:]    모든 대문자([A-Z])
  • [:xdigit:]    모든 16진수 숫자([a-fA-F0-9])





전방탐색과 후방탐색


  • (?=)    긍정형 전방 탐색
  • (?!)    부정형 전방 탐색
  • (?<=)    긍정형 후방 탐색
  • (?<!)    부정형 후방 탐색




조건 사용하기


  • (?(backreference)true)    역참조가 있을 때 true를 함께 일치시킴
  • (?(backreference)true|false)    역참조가 있을 때 true를 아니면 false를 일치시킴
  • (?(?=식)true|false)    전방탐색을 이용한 조건
  • (?(?<=식)true|false)    후방탐색을 이용한 조건




자바에서 정규표현식 사용


※ JRE 1.4부터 정규표현식을 지원하므로 유의하여 사용한다.

※ 조건은 지원하지 않음

※ \E, \l, \L, \u, \U를 이용한 대소문자 변환은 지원하지 않음

※ \b를 이용한 백스페이스 일치를 지원하지 않음

※ \z는 지원하지 않음


java.util.regex.Matcher 클래스

  • find() - 문자열에서 패턴과 일치하는 부분이 있는지 찾는다.
  • lookingAt() - 문자열이 주어진 패턴으로 시작하는지 일치시켜 본다.
  • matches() - 문자열 전체를 주어진 패턴과 일치시켜본다.
  • replaceAll() - 일치하는 부분을 모두 치환한다.
  • replaceFirst() - 처음 일치하는 부분만 치환한다.
  • group() - 하위 표현식을 반환한다.


java.util.regex.Pattern 클래스

  • compile() - 정규 표현식을 패턴으로 컴파일한다.
  • flag() - 패턴에 설정되어 있는 일치 플래그를 반환한다.
  • matches() - Matcher 클래스의 matches와 동일함
  • pattern() - 만들었던 패턴에서 정규 표현식 부분을 문자열로 반환한다.
  • split() - 문자열을 하위 문자열로 나눈다.



import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexTest{     public static void main(String[] args){         Pattern pattern = Pattern.compile("정규표현식");         Matcher matcher = pattern.matcher("대상 문자열");         if(matcher.find()){             // 처리         }     } }




'밤을 지새다' 카테고리의 다른 글

Linux Kernel Map  (0) 2013.03.24
C# ListBox Double Click 이벤트  (0) 2012.06.08
네이트온 광고와 팝업 없애기  (3) 2012.05.16
파일의 확장자를 보는 방법  (0) 2012.05.16
Gmail 실행파일 첨부 문제  (0) 2012.05.16

안드로이드에서 EditText와 같은 뷰를 가진 액티비티가 시작되면 소프트 키보드가 항상 보이는 채로 시작된다.

키보드가 보이지 않는 채로 액티비티를 시작하고 싶다면

Activity를 상속받은 클래스에서 onResume 메서드를 아래와 같이 오버라이딩 한다.

@Override protected void onResume(){     super.onResume();     getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); }


만약 특정 순간(이벤트 처럼) 후에 키보드를 감추거나 보이게 할 때는 아래와 같이 하면 된다.

// InputMethodManager를 가져옴 InputMethodManager imm =     (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); // 감출 때 imm.hideSoftInputFromWindow(ViewName.getWindowToken(), 0); // 보이게 할 때 imm.showSoftInput(ViewName, 0);



+ 2012.06.10 추가

애초에 포커스를 EditText로 주지 않는 방법도 있다.

해당 액티비티의 레이아웃 파일에서 레이아웃에 focusable, focusableInTouchMode 애트리뷰트를 추가하고

값을 true로 주고 requestFocus 태그를 추가한다.


<LinearLayout

        ... 다른 속성들

        android:focusable="true"

        android:focusableInTouchMode="true">

        <requestFocus/>


       ...

</LinearLayout>


이는 포커스를 가질 수 없는 레이아웃에 강제로 포커스를 가지게 하고 포커스를 줌으로써

EditText가 포커스를 가지지 않게하여 소프트 키보드를 보이지 않게 하는 방법이다.

+ Recent posts