C++/공부
Qt에서 TinyXML2를 사용한 XML 읽기와 쓰기 예제 정리
Lewisjkim
2025. 5. 13. 14:23
TinyXML2는 경량 XML 파서로, Qt 기반 애플리케이션에서도 쉽게 사용할 수 있습니다. 이번 글에서는 TinyXML2를 사용하여 XML 파일을 읽고 쓰는 기본적인 방법을 정리합니다.
1. TinyXML2 설치 및 프로젝트에 추가
TinyXML2는 단일 헤더/소스 구조로 되어 있어 프로젝트에 쉽게 포함할 수 있습니다.
git clone https://github.com/leethomason/tinyxml2.git
Qt 프로젝트에서는 .pro 파일 또는 CMakeLists.txt에 tinyxml2 소스파일을 직접 추가하면 됩니다.
2. XML 파일 읽기
예시 XML:
<config>
<user name="admin" password="1234"/>
</config>
#include <tinyxml2.h>
using namespace tinyxml2;
XMLDocument doc;
doc.LoadFile("config.xml");
XMLElement* root = doc.FirstChildElement("config");
XMLElement* user = root->FirstChildElement("user");
const char* name = user->Attribute("name");
const char* password = user->Attribute("password");
3. XML 파일 쓰기
XMLDocument doc;
XMLElement* root = doc.NewElement("config");
doc.InsertFirstChild(root);
XMLElement* user = doc.NewElement("user");
user->SetAttribute("name", "admin");
user->SetAttribute("password", "1234");
root->InsertEndChild(user);
doc.SaveFile("config.xml");
4. 주의사항
- LoadFile()이나 SaveFile()은 파일 경로에 따라 실패할 수 있으므로, 반환값을 항상 체크하는 것이 좋습니다.
- Qt의 QString을 사용할 경우, toStdString().c_str() 또는 toUtf8().constData()로 변환 필요
TinyXML2는 가볍고 빠르며, Qt 프로젝트에 쉽게 통합할 수 있다는 점에서 매우 유용한 XML 처리 라이브러리입니다.