在 javascript 中获取 xml 标记名称

Getting xml tag names in javascript

本文关键字:xml javascript 获取      更新时间:2023-09-26

我一直试图在java脚本中获取标签名称及其值。我使用的 xml 文件如下所示:

<root>
    <note>
        <to>Gil</to>
        <from>
            <firstname>john</firstname>
            <lastname>corner</lastname>
        </from>
        <heading>Reminder</heading>
    </note>
    <note>
        <to>Mary</to>
        <from>
            <firstname>Clara</firstname>
            <lastname>Diana</lastname>
        </from>
        <heading>
            How are you
        </heading>
    </note>
</root>

我希望输出如下:

TageName : root Attribute: 0 Text: null
TageName : note Attribute: 0 Text: null
TageName : to   Attribute: 0 Text: Gil
TageName : from Attribute: 0 Text: null
TageName : firstname Attribute: 0 Text: john
TageName : lastname Attribute: 0 Text: corner
TageName : heading Attribute: 0 Text: Reminder
TageName : note Attribute: 0 Text: null
TageName : to   Attribute: 0 Text: Mary
TageName : from Attribute: 0 Text: null
TageName : firstname Attribute: 0 Text: Clara
TageName : lastname Attribute: 0 Text: Diana
TageName : heading Attribute: 0 Text: How are you

这可能吗。如果是这样,请帮助我...

var xml = '<root><note ><to>Gil</to><from><firstname>john</firstname><lastname>corner</lastname></from><heading>Reminder</heading></note><note><to>Mary</to><from><firstname>Clara</firstname><lastname>Diana</lastname></from><heading>How are you</heading></note></root>';
var node = (new DOMParser()).parseFromString(xml, "text/xml").documentElement;
var nodes = node.querySelectorAll("*");
for (var i = 0; i < nodes.length; i++) {
    var text = null;
    if (nodes[i].childNodes.length == 1 && nodes[i].childNodes[0].nodeType == 3) //if nodeType == text node
        text = nodes[i].textContent; //get text of the node
    console.log("TageName : ", nodes[i].tagName, ", Text : ", text);
}​

这是一个jsFiddle,显示了基本用法。 以下是使用 jQuery 的基本代码:

$(document).ready(function()
{
    $(this).find("root").children().each(function()
     {
             alert($(this).get(0).tagName+":"+$(this).text());                                 
       });                                                                                     
 });

修改它以满足您的需求。