프레임워크/Spring

[Spring] 문서의 요소 콘텐츠에서 부적합한 XML 문자

pythaac 2022. 1. 28. 01:19

[에러] 문서의 요소 콘텐츠에서 부적합한 XML 문자(유니코드: 0x14)가 발견되었습니다. (An invalid XML character (Unicode: 0x14) was found in the element content of the document.)

  Tistory API의 결과를 XML로 받아오며 아래와 같은 방식으로 XML String(xml)을 파싱하여 사용하였습니다.

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

InputStream is = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
Document doc = builder.parse(is);
doc.getDocumentElement().normalize();

그러던 중 아래와 같이 XML 파서가 처리할 수 없는 데이터를 포함하고 있다는 에러 메시지를 확인했습니다.

 

[원인] 유니코드 0x14

  원인은 명확하게 xml 문서 내에 xml이 정의하지 않는 문자가 포함되어 있어 생긴 문제였습니다. XML로 수신한 API 응답에 이런 문제가 포함될 수 있나?라는 의문을 가지며 해당 문자를 찾아보았습니다.

문제가 발생한 XML 내용을 바탕으로 해당 내용이 포함된 글을 찾아보았습니다. 육안으로 보았을 때는 문제가 없었으며, 내용이 잘려나와 문제되는 문자를 볼 수 없었습니다. 그래서 해당 링크를 들어가서 보았더니 아래와 같은 문자가 포함되어 있었습니다.

 

[해결] replace로 제거

  저는 해당 문자를 찾아 제거하는 방식을 사용했습니다. 그러나 더 좋은 방법은 Regex를 통해 XML 문자로 정의되지 않은 모든 문자들을 찾아 제거하도록 설정하는 것이 안전할 것 같습니다.

 

[참고] 유니코드 0x14

  XML이 처리하지못한 유니코드 0x14는 기본 로마자(Basic Latin)에 속하는 DC4(Device Control 4)라는 문자였습니다.

https://unicode-table.com/en/0014/

 

 - Device Control Four: U+0014

Symbol: , Name of the character: device control four, Unicode number for the sign: U+0014, the icon is included in the block: Basic Latin.

unicode-table.com

 

[참고] XML 문자

https://www.w3.org/TR/xml11/#charsets

 

Extensible Markup Language (XML) 1.1 (Second Edition)

Extensible Markup Language, abbreviated XML, describes a class of data objects called XML documents and partially describes the behavior of computer programs which process them. XML is an application profile or restricted form of SGML, the Standard General

www.w3.org

  XML이 정의하는 문자는 정해져있으며 데이터를 주고받으며 파싱할 때 이러한 문자에 대해 신경써야할 듯 합니다.