0

I tried using jQuery parse but, it is helpful only when searching by a value or when element name is known in advance.

I need to obtain root element name itself from the document. How do I achieve this? I can do string arithmetic to get this out, but it would not be reliable approach in production code.

0

2 Answers 2

1

This is a pure JavaScript solution for your problem (I hope).

JSFiddle

// The initial string
var xmlString = '<?xml version="1.0" ?><myRoot><someNode></someNode></myRoot>';

// Parse the string with the function defined below
var doc = parseXml(xmlString);

// Extract the name of the root element
var rootName = doc.documentElement.nodeName;

alert(rootName); // Alerts "myRoot" in this example

// Cross-browser function to parse an XML string
function parseXml(xmlString) {
    var doc;
    if (window.ActiveXObject) {
        // Internet Explorer
        doc = new ActiveXObject("MSXML.DOMDocument");
        doc.async = false;
        doc.loadXML(xmlString);
    } else {
        // Other browsers
        var parser = new DOMParser();
        doc = parser.parseFromString(xmlString, "text/xml");
    }
    return doc;
}
Sign up to request clarification or add additional context in comments.

Comments

0

can you check this example

var xml = '<xml><thing>stuff</thing><thing2>value</thing2></xml>';
var firstNodeName = $(xml).attr("nodeName");
alert("The first node name is: " + firstNodeName );

it return "XML"

Demo

2 Comments

For string, it worked fine, but for xml document like below.. code does not work var xml = "<?xml version='1.0'?><xml><thing>stuff</thing><thing2>value</thing2></xml>";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.