XML Services
XML interfaces in ClanLib:
- Document Object Model (DOM)
- XML Tokenizer
- XML Writer
Document Object Model
ClanLib supports the W3C DOM API, so most people should feel right at home when dealing with XML. In general, to get documentation about the DOM API functions, see the DOM Level 2 Core Specification.
Although there exists a ton of tutorials out on the web describing how to use the DOM API, it might be useful to get a quick glance at how it looks like in ClanLib.
Consider the following XML file.
<example:envelope xmlns:example="http://clanlib.org/example"> <example:body> <example:message name="msg1">value1</example:message> <example:message name="msg2">value2</example:message> </example:body> </example:envelope>
To load this XML file and retrieve the names and values of the messages, the syntax would be as follows:
CL_String ns_example = "http://clanlib.org/example"; CL_File file("example.xml", CL_File::open_existing); CL_DomDocument document(file); CL_DomElement root = document.get_document_element(); CL_DomElement body = root.named_item_ns(ns_example, "body").to_element(); CL_DomNode cur = body.get_first_child(); while (cur.is_node()) { if (cur.get_namespace_uri() == ns_example && cur.get_node_name() == "message") { CL_DomElement element = cur.to_element(); CL_String name = element.get_attribute_ns(ns_example, "name"); CL_String value = element.get_text(); CL_Console::write_line("Message %1: %2", name, value); } cur = cur.get_next_sibling(); }
XML Tokenizer and Writer
A XML file can also be read using the CL_XMLTokenizer class. It reads the nodes of a XML file as tokens and returns those to the application. I.e. to print all the names of all nodes in a XML file:
CL_File file("example.xml", CL_File::open_existing); CL_XMLTokenizer tokenizer(file); while (true) { CL_XMLToken token = tokenizer.next(); if (token.type == CL_XMLToken::NULL_TOKEN) break; if (token.type == CL_XMLToken::ELEMENT_TOKEN && token.variant != CL_XMLToken::END) { CL_Console::write_line("Element: %1", token.name); } }
A XML file can also be written by feeding CL_XMLWriter with CL_XMLToken objects describing the XML file. For example, the following example strips all attributes:
CL_File file_input("example.xml", CL_File::open_existing); CL_File file_output("example-out.xml", CL_File::create_always); CL_XMLTokenizer tokenizer(file_input); CL_XMLWriter writer(file_output); while (true) { CL_XMLToken token = tokenizer.next(); if (token.type == CL_XMLToken::NULL_TOKEN) break; if (token.type == CL_XMLToken::ELEMENT_TOKEN) token.attributes.clear(); writer.write(token); }