简体   繁体   中英

Given a string representing an XML file, what's the easiest way to locate all namespace declarations with Javascript or jQuery?

I've got a webpage which reads an XML file and loads the contents into a div on the page. As a part of this process, I need to identify all of the namespace prefixes and corresponding URIs declared in that file. I'm using jQuery to get and load the file like this:

$.get(sourceURI, function (data) {
    var nsList = getNamespaces(data);
    var target = $('#my_div');
    target.html(data);
});

where getNamespaces is a function taking the result of the get, and returning an object in the form:

object = {
    prefix1: uri1, //e.g xmlns:foo="http://bar.com" -> { foo: "http://bar.com" }
    prefix2: uri2,
    ....
    prefixn: urin
}

I have a sinking feeling that the answer may be a regex, but obviously that requires me to write one, and suffer over-used adages about having two problems from my colleagues. Is there a better way, or if not could someone point me in the right direction in constructing a regex?

Thanks!

If your browser is XHTML-compliant, you can use its parsing facilities to iterate over the XML elements with jQuery instead of processing a raw string with regular expressions:

function getNamespaces(data)
{
    var result = {};
    $(data).each(function() {
        recurseGetNamespaces(this, result);
    });
    return result;
}

function recurseGetNamespaces(element, result)
{
    var attributes = element.attributes;
    for (var i = 0; i < attributes.length; ++i) {
        var attr = attributes[i];
        if (attr.name.indexOf("xmlns:") == 0) {
            var prefix = attr.name.substr(6);
            if (!(prefix in result)) {
                result[prefix] = attr.value;
            }
        }
    }
    $(element).children().each(function() {
        recurseGetNamespaces(this, result);
    });
}

You can find a fiddle demonstrating this method here . ( Disclaimer: that fiddle uses JSON.stringify() to display the results, so that part of the code might not work with browsers other than Firefox).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM