// E40-XML.cpp -- demonstrates the use of XML import, export and manipulation

#include <Platform.h>
using namespace Platform;


// define an original (and perfectly valid) XML text
const Char* xml = appText("<?xml version=\"1.0\"?><!-- comment --><root><test><node name=\"a\">0</node><node name=\"b\">11</node><node name=\"c\">222</node></test></root>");


// program entry point
//====================================================================================================
AppMain(args)
{
    // first, export the original XML string to a file "test.xml"
    Text::exportString(Path(appText("test.xml")), xml);


    // import the file we've just created and construct an XML document from the text in that file
    Text::Xml::Document document(Text::importString(Path(appText("test.xml"))));

    // reformat the XML document applying all possible transformations
    //  formatting can be useful to normalize newlines, strip whitespace, remove comments etc
    document.reformat(Text::Xml::ReformatFlags_All);


    // locate an element within the XML document
    //  this works similar to using a file path to locate a certain file in a file system
    //
    // you can use wildcards for partial name matching (symbols '*' and '?')
    //  and to find a certain sibling element you can use an #N suffix where N is the Nth
    //  element in the XML tree
    //
    // the index is zero based for positive numbers (i.e. name#0 selects the first matching
    //  XML element
    // negative numbers (as in e.g. name#-3) search in reverse order, hence to access
    //  the last element at a certain depth in the tree you would use #-1
    //
    // attributes are enclosed in brackets and immediately follow the name of a node, e.g.
    //  root/node1<attrA=valueA><attrB=valueB>/node2<attrC>
    Text::Xml::Element* element = document.select("root/*/node#1")[0];


    // if the element is found (and it will be in the original xml) print it's path to the root
    //  and the text value
    if(element != Null)
        Runtime::StdOut::println(appText("found element: '") + element->path() + appText("' with text: ") + element->text());

    // to export an XML document we probably want to specify the encoding of the output file
    Text::Encoding encoding = Text::Encoding_UTF8;

    // put the encoding into the XML document declaration (as an attribute)
    document.attributes.put(appText("encoding"), Text::encodingToString(encoding));

    // finally, convert the XML document to string (the True argument in toString generates
    //  pretty-printed XML text) and save the result to a file named "test-out.xml"
    Text::exportString(Path("test-out.xml"), document.toString(True), encoding);

    return 0;
}


/* EOF */