Cpp:XmlCppLib:TutorialFrom IdeA thinKING
Introduction"XML C++ Library"(이하 xmlcpp)는 C++ 언어를 위한 XML parser입니다. 아직 자체내의 parsing engine을 가지고 있지 않으며 외부의 존재하는 XML parser를 내부에 사용하여 STL의 container와 같은 인터페이스를 제공합니다. 이 페이지에서는 xmlcpp가 제공하는 인터페이스에 대해 간단히 소개합니다. Basic Concept먼저 하나의 XML 문서는 node들로 구성됩니다. node에는 document, declaration, element, text, comment, unknown 타입들이 있습니다. 실제 XML 문서의 node는 아니지만 null 타입 node가 몇 몇 함수에서 사용하는 Null Object design pattern 구현을 위해 존재합니다. 이들 node 클래스외에 exception 클래스와 attribute 클래스가 존재합니다. XML 문서의 예를 보면 다음과 같습니다. <!-- document node --> <?xml version="1.0"?> <!-- declaration node --> <collection> <!-- element node --> <!-- collection of recipes --> <!-- comment node --> ... <recipe> <!-- element node --> ... <comment> <!-- element node --> Make the meat ahead of time, and <!-- text node --> </comment> <nutrition calories="1167" fat="23" /> <!-- element node with attributes --> </recipe> </collection> document node는 전체 XML 문서를 나타냅니다. element node는 각 element를 나타내며 child node를 가질 수 있습니다. 또한 element node는 attribute을 가질 수 있습니다. declaration node는 version이나 encoding, standalone 정보를 가질 수 있습니다. 나머지 comment, text, unknown node들은 자신만의 value외에 특별한 정보를 가지고 있지 않습니다. XML Open먼저 XML 문서를 열기 위해 다음과 같은 방법을 사용합니다. using namespace xmlcpp; node_document doc("recipes.xml"); // or node_document doc; doc.load_file("recipes.xml"); 혹은 메모리상의 XML 데이터를 읽기 위해서는 다음과 같이 parse() 함수를 사용합니다. char const* data = "..."; node_document doc; doc.parse(data); Traversing And SearchingNode Iterator위에서 얻은 node_document 객체를 가지고 child node들을 다음과 같이 iterator를 사용하여 얻을 수 있습니다.[1] for (node_base::iterator i = doc.begin(); i != doc.end(); ++i) { node_base& node = *i; } node_base는 모든 node 클래스들의 parent class입니다. node_base는 child node들의 iteration을 위해 다음과 같은 타입의 iterator들을 제공합니다.
Element Iterator이외에 element node들만을 iterate 하고자 할 때 사용할 수 있는 elem_iterator 들도 제공합니다.
만약 "collection"라는 value를 가진 child node를 찾고자 한다면 다음과 같이 stl의 알고리즘을 사용할 수 있습니다.[1] node_base::iterator i = find_if(doc.begin(), doc.end(), value_equal_to("collection")); if (i != doc.end()) ... Seraching하지만 이런 식으로 child node를 계속 따라가며 검색하는 것은 조금 번거롭습니다. 따라서 다음과 같이 cascading을 지원하는 get_node() 함수를 제공합니다. node_base& node = doc.get_node("collection").get_node("recipe").get_node("comment"); if (node.get_node_type() == node_base::null_type) ... 이때 중간에 값이 없더라도 cascading이 이루어지도록 하기 위해 null object design pattern이 사용됩니다. 따라서 이 경우엔 결과로 받은 node의 type이 null type인지를 검사해야 합니다. 위의 코드를 좀 더 간단하게 작성할 수 있도록 get_node() 함수의 wrapper인 operator()를 제공합니다. 위의 코드는 아래처럼 간단하게 작성될 수 있습니다. node_base& node = doc("collection")("recipe")("comment"); if (node.get_node_type() == node_base::null_type) ... 만약 같은 이름을 가진 child node가 둘 이상이라면 get_node() 함수나 operator()에 추가로 index parameter를 사용할 수 있습니다. 이 index는 0-based로 동작합니다. node_base& node = doc("collection")("recipe", 1); if (node.get_node_type() == node_base::null_type) ... Attibutenode들 중 element_node는 특별히 attr_iterator를 추가로 제공합니다.[1] 사용법의 예를 들면 다음과 같습니다. node_base& node = doc("collection")("recipe")("nutrition"); if (node.get_node_type() == node_base::element_type) { node_element& elem = dynamic_cast<node_element&>(node); for (node_element::attr_iterator i = elem.attr_begin(); i != elem.attr_end(); ++i) { attribute& attr = *i; } } 또한 element_node는 특정 name을 가진 attribute를 찾을 때 사용할 수 있는 find() 함수도 제공합니다. 각 attribute 클래스는 get_name()과 get_value()함수를 제공하며 각 리턴 타입은 char const*입니다. 만약 value를 int 타입으로 읽고 싶다면 다음과 같이 template method를 사용할 수 있습니다.[1] string s = attr.get_value(); int n = attr.get_value<int>(); 이번 글에서 설명한 iterator, elem_iterator, attr_iterator family들은 모두 bidirectional iterator category입니다. Visitor위에서 설명한 내용외에 Visitor design pattern을 node class들에서 제공하여 node에 대한 추가 operation이 필요한 경우 사용자들이 직접 구현할 수 있도록 했습니다. ostream에 XML 문서를 들여쓰기하여 출력할 수 있는 기능이 node_printer라는 node_visitor 클래스의 구현을 통해 제공됩니다.
Conclusion이상이 현재까지 구현된 내용의 소개입니다. 아직 주로 XML DOM 트리를 읽는 방법들입니다. 앞으로 DOM 트리를 생성할 수 있는 interface를 만들 예정입니다. 관심 있으신 분들은 개선 사항이나 추가 구현이 필요한 내용을 알려 주시면 반영해 보도록 하겠습니다. Related SitesFoot Notes |

