How to use jQuery for XML parsing with namespaces

后端 未结 20 1785
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 10:17

I\'m new to jQuery and would like to parse an XML document.

I\'m able to parse regular XML with the default namespaces but with XML such as:



        
20条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 10:42

    In case someone needs to do this without jQuery, just with normal Javascript, and for Google Chrome (webkit), this is the only way I found to get it to work after a lot of research and testing.

    parentNode.getElementsByTagNameNS("*", "name");

    That will work for retrieving the following node: . As you can see the prefix or namespace is omitted, and it will match elements with different namespaces provided the tag name is name. But hopefully this won't be a problem for you.

    None of this worked for me (I am developping a Google Chrome extension):

    getElementsByTagNameNS("prefix", "name")

    getElementsByTagName("prefix:name")

    getElementsByTagName("prefix\\:name")

    getElementsByTagName("name")

    Edit: after some sleep, I found a working workaround :) This function returns the first node matching a full nodeName such as :

    // Helper function for nodes names that include a prefix and a colon, such as ""
    function getElementByNodeName(parentNode, nodeName)
    {   
        var colonIndex = nodeName.indexOf(":");
        var tag = nodeName.substr(colonIndex + 1);
        var nodes = parentNode.getElementsByTagNameNS("*", tag);
        for (var i = 0; i < nodes.length; i++)
        {
            if (nodes[i].nodeName == nodeName) return nodes[i]
        }
        return undefined;
    }
    

    It can easily be modified in case you need to return all the matching elements. Hope it helps!

提交回复
热议问题