簡體   English   中英

給定一個表示XML文件的字符串,用Javascript或jQuery查找所有名稱空間聲明的最簡單方法是什么?

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

我有一個網頁,該網頁讀取XML文件並將內容加載到頁面上的div中。 作為此過程的一部分,我需要標識該文件中聲明的所有名稱空間前綴和相應的URI。 我正在使用jQuery來獲取和加載文件,如下所示:

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

其中,getNamespaces是一個獲取get結果並以以下形式返回對象的函數:

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

我有一個下沉的感覺,答案可能是一個正則表達式,但是顯然這需要我寫一個正則表達式,並且遭受了同事們提出的兩個問題的過度使用的格言。 有沒有更好的方法,或者如果沒有,有人可以指出我構建正則表達式的正確方向嗎?

謝謝!

如果您的瀏覽器兼容XHTML,則可以使用其解析工具通過jQuery遍歷XML元素,而無需使用正則表達式處理原始字符串:

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);
    });
}

您可以在此處找到展示此方法的小提琴。 免責聲明:小提琴使用JSON.stringify()來顯示結果,因此部分代碼可能不適用於Firefox以外的瀏覽器)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM