在javascript中获取xml标记名称

时间:2012-07-02 13:27:44

标签: javascript xml-parsing

我一直在尝试在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

这可能吗?如果是的话,请帮助我......

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

这是显示基本用途的jsFiddle。这是使用jQuery的基本代码:

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

修改它以满足您的需求。