XML API 응답 개수가 DB 조회 개수와 달라요

StringEscapeUtils.escapeXML10

web
featured
xml
escapeXml10
unescapeXml
spring
StringEscapeUtils
Apache Commons
Author

Yunho Kee

Published

May 5, 2024

Intro

2021년 해군 소프트웨어개발병 시절 후임을 돕다 발견한 문제이다.

DB에서 조회되는 일부 항목이 왜 XML 응답에는 안 보일까?

Problem Analysis

A screenshot of the expected xml api response.

예상 XML API 응답

A screenshot of the real xml api response.

실제 XML API 응답
Figure 1: Browser의 XML Parse 실패

사실 응답은 도착했다. 다만 Browser에서 XML Parse에 실패해 누락됐다.

Solution

다음과 같이 StringEscapeUtils.escapeXml10을 거치면 문제가 되는 유니코드 문자가 제거 또는 Escape된다. 그리고 StringEscapeUtils.unescapeXml로 일부 복원한다.

package yhkee0404.escapexml10.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.apache.commons.text.StringEscapeUtils;

@RestController
@RequiredArgsConstructor
public class XMLController {

    private static final String unicodeXML = 
            "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
            + "<post>"
            + "<title>BACK\u0008SPACE</title>"
            + "<text>EXCLAMATION\u0021MARK</text>"
            + "</post>";

    @GetMapping(value = "/xml", produces = MediaType.APPLICATION_XML_VALUE)
    public String xml() {
        // return unicodeXML;
        return StringEscapeUtils.unescapeXml(StringEscapeUtils.escapeXml10(unicodeXML));
    }
}

Deprecate된 org.apache.commons.lang3.StringEscapeUtils에서 escapeXML도 확인할 수 있다. 이제는 org.apache.commons.text.StringEscapeUtils로 이동했다.

한편 EscapeXml11도 있다. 그러나 DevSecOps Engineer Lee (2012) 에 따르면 XML 1.1은 권장되지 않는다. 그리고 MDN Web Docs (2023) 에 따르면 Browser 지원도 없다.

Back to top

References

Lee, Linus. 2012. “XML 1.0을 써야하는 이유.” April 12, 2012. https://andromedarabbit.net/2012/04/12/xml-1-0%ec%9d%84-%ec%8d%a8%ec%95%bc%ed%95%98%eb%8a%94-%ec%9d%b4%ec%9c%a0/.
MDN Web Docs. 2023. “Document: xmlVersion Property.” April 7, 2023. https://developer.mozilla.org/en-US/docs/Web/API/Document/xmlVersion.

Citation

BibTeX citation:
@online{kee2024,
  author = {Kee, Yunho},
  title = {XML API 응답 개수가 DB 조회 개수와 달라요},
  date = {2024-05-05},
  url = {https://yhkee0404.github.io/posts/web/escape-xml10},
  langid = {ko}
}
For attribution, please cite this work as:
Kee, Yunho. 2024. “XML API 응답 개수가 DB 조회 개수와 달라요.” May 5, 2024. https://yhkee0404.github.io/posts/web/escape-xml10.