-2

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

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

4

2 回答 2

5
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);
}​
于 2012-07-02T13:45:36.997 回答
0

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

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

修改它以满足您的需求。

于 2012-07-02T13:37:31.647 回答