I am currently working on developing a recursive function that takes an HTML document tree and generates formatted CSS using only child operators (>), but I seem to be stuck. If you could provide some hints or ideas, I would greatly appreciate it.
The main concept is to transform something like this:
body
/ \
div div
/ \ / \ \
h1 p p ul div
/ \
li li
into:
div
div > h1
div > p
div > p
div > ul
div > ul > li
div > ul > li
div > div
Alternatively, in string format:
"div\n\t div > h1\n\tdiv > p\n\tdiv > p\n\tdiv > ul\n\t\tdiv > ul > li\n\t\tdiv > ul > li\n\tdiv > div"
I already have a method for retrieving the 'body' and its corresponding tree structure. The necessary functions are part of an object named XMLNode
:
getChildNode(int k)
: returns theXMLNode
object representing the kth child. Returns a special object if none exists.isEmpty()
.getName()
: retrieves the node name as a string-like object that can be converted into a string.
My current approach involves calling:
std::cout << tree2CSS(bodyNode);
where the tree2CSS
function is defined as follows:
std::string tree2CSS(XMLNode & rootNode, unsigned depth = 0)
{
int i = 1;
XMLNode childNode = rootNode.getChildNode(i);
std::string accumCSS;
while (!childNode.isEmpty())
{
std::string tabs(depth, '\t');
accumCSS.append("\n" + tabs);
if (depth > 0) accumCSS.append(" > ");
accumCSS.append((std::string)childNode.getName() + tree2CSS(childNode, depth + 1));
childNode = rootNode.getChildNode(++i);
}
return accumCSS;
}
Unfortunately, this implementation seems to be failing, and I cannot pinpoint the issue. Any assistance would be greatly appreciated.