0

I have a jQuery recursive function which parses my xml data however I am trying to select the children of the child element, so basically the element inside the element. for instance in the xml I want to select <to> tag, so I can indent and add a expand collapse button.

xml

<?xml version="1.0" encoding="UTF-8"?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

jQuery

function traverse(tree) {
            $(tree).contents().each(function (i, child) {
                    if (child.nodeType == 3) { // text node

                        $("#xml-reader").append(
                            '<span>' + child.nodeValue + '</span>'
                        );

                        // this is my attempt
                        if (child.children) { // element node
                            $("#xml-reader").append(
                                '<br><i>' + child.nodeName + ": " + '</i>'
                            );
                        }
                    } else {
                        if (child.nodeType === 8) { // comment node

                            $("#xml-reader").append(
                                '<i>' + child.nodeValue + '</i>'
                            );
                        }
                        else {
                            $("#xml-reader").append(
                                '<br><b>' + child.nodeName + ": " + '<b>'
                            );
                            traverse(child);
                        }
                    }
                }
            );
        }

        traverse($(xml).find('*'));
  • 1
    `child.children` when you want to access the children of a node then it should be a function: `child.children()`. If child is an object containing the nodes then you could access it via `child.to`. To verify that can you set up an example or specify the content of `tree` or `child` inside the `.each()`? – empiric Feb 13 '17 at 15:04
  • @empiric I rewrote the whole function. I now have a recursive function that will parse any xml file and output the file in the browser as an expandable tree. – Stephen Ó Connor Mar 01 '17 at 09:50

1 Answers1

0

I rewrote my traverse function using this SO answer JavaScript Recursion to format lists from XML to HTML One major change was changing this if statement

if( node.childNodes[index].tagName == 'name' ) {

to

if (node.nodeType === Node.TEXT_NODE)

This way I can read in any xml file regardless of the tagName

Community
  • 1
  • 1