반응형

dependency

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.2.3</version>
</dependency>

파싱할 XML 본문

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<result>
    <response>
        <code>200</code>
    </response>
    <map_id>Savage_Main</map_id>
    <deaths>
        <death>
            <time_event>250</time_event>
            <is_range_valid>true</is_range_valid>
            <description>QBZ</description>
        </death>
        <death>
            <time_event>562</time_event>
            <is_range_valid>true</is_range_valid>
            <description>QBZ</description>
        </death>
    </deaths>
</result>

Model 클래스

@Data
@XmlAccessorType(XmlAccessType.FIELD)
public class GameResult {
    @XmlElement(name = "response")
    private GameResponse response;
    @XmlElement(name = "map_id")
    private String mapId;
    @XmlElementWrapper(name = "deaths")
    @XmlElement(name = "death")
    private List<GameDeath> deathList;
}
@Data
@XmlAccessorType(XmlAccessType.FIELD)
public class GameResponse {
    @XmlElement(name = "code")
    private int code;
}
@Data
@XmlAccessorType(XmlAccessType.FIELD)
public class GameDeath {
    @XmlElement(name = "time_event")
    private int timeEvent;
    @XmlElement(name = "is_range_valid")
    private boolean isRangeValid;
    @XmlElement(name = "description")
    private String description;
}

parse 메소드 코드

private static <T> T parse(String xml, String rootField, Class<T> type) {
    XMLStreamReader reader = null;

    try {
        reader = XMLInputFactory.newFactory().createXMLStreamReader(new StringReader(xml));

        while (reader.hasNext()) {
            if (reader.isStartElement() && reader.getLocalName().equals(rootField)) {
                break;
            }

            reader.next();
        }

        Unmarshaller unmarshaller = JAXBContext.newInstance(type).createUnmarshaller();

        JAXBElement<T> rootElement = unmarshaller.unmarshal(reader, type);

        return rootElement.getValue();
    } catch (Exception e) {
        throw new IllegalStateException(e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (XMLStreamException e) {
                throw new IllegalStateException(e);
            }
        }
    }
}

xml to object

GameResult gameResponse = parse(xml, "result", GameResult.class);

xml to object (with root property)

GameResponse gameResponse = parse(xml, "response", GameResponse.class);
반응형

'Development > Java' 카테고리의 다른 글

[Java] VisualVM 사용하기  (0) 2019.09.30
[Java] JDK 버전별 신규 기능  (0) 2019.04.21
[Java] Json Handling(with Jackson)  (0) 2019.03.20
[Java] HTML 파싱  (0) 2019.03.20
[Java] Garbage Collector  (0) 2018.07.24

+ Recent posts