在javascript中读取XML属性 [英] reading XML attributes in javascript

查看:85
本文介绍了在javascript中读取XML属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

猜猜这是一个简单的问题,对于一个javascript大师,但我正在学习并遇到一个我无法猜到的问题。

Guess it's a simple question for a javascript guru, but i'm learning and got a problem I can't guess out.

我有兴趣阅读使用javascript的XML文件。以下是XML文件的示例:

I'm interested in reading an XML file using javascript. Here is an example of the XML file:

<object name='obj1'>
   <attribute name='att1' value='val1'/>
   <attribute name='att2' value='val2'/>
   <attribute name='attN' value='valN'/>
   <subobject name='sub1'>
          <attribute name='satt1' value='sval1'/>
          <attribute name='satt2' value='sval2'/>
          <attribute name='sattN' value='svalN'/>
   </subobject>
   <subobject name='subn'>
          <attribute name='snatt1' value='snval1'/>
          <attribute name='snatt2' value='snval2'/>
          <attribute name='snattN' value='snvalN'/>
   </subobject>
</object>

如你所见,我有N个对象。每个对象都有全局属性,并且可能有0 ... M个子对象及其属性。

As you can see, I have N objects. Each object has global attributes, and may have 0...M subobjects with their attributes.

问题是,应用此(我的)代码来解析 ob1 属性,我也获得所有子对象属性:

Problem is, applying this (my) code to parse ob1 attributes, I also get all subobject attributes:

if (window.XMLHttpRequest) {    
    var xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET",URL,false);  
    xmlhttp.send();

    var xmlDoc=xmlhttp.responseXML;

    var objList = xmlDoc.getElementsByTagName("object");
    var attrList = objList[0].getElementsByTagName("attribute"); // Got ALL attributes here
}

在该代码中(为简单起见,没有错误测试) ,我的attrList对象同时获取obj1和所有子对象属性。

In that code (no error test for simplicity), my attrList object gets both obj1 and all subobject attributes.

如何重写代码才能获得att1 ... attN?!?!

How can I rewrite the code to get only att1...attN?!?!

提前致谢!

推荐答案

在这种情况下,因为属性您要查找的元素是对象元素的直接子元素,您可以做的一件简单事情就是遍历子元素 object 手工元素:

In, this case, since the attribute elements you are looking for are direct children of the object element, a simple thing you can do is iterate through the child elements of the object element by hand:

var obj = objList[0]
var childNodes = obj.childNodes
for(var i=0; i<childNodes.length; i++){
    var child = childNodes[i];
    if(child.nodeType == 1 && child.nodeName == 'attribute'){
        do_something(child);
    }
}

有关这些和其他DOM方法的信息,我建议在 MDN 上查看文档。

For information on these and other DOM methods, I recommend checking out the documentation over on MDN.

这篇关于在javascript中读取XML属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆