简体   繁体   中英

reading XML attributes in javascript

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

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>

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

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
}

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

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

Thanks in advance!

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

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

The problem you are running into is that technically "attributes" of subobject are also children of object. Remember that any element is a Node object, and on that Node you can get all childNodes. You can do that and process each "Element" node and determine if it is an "attribute" Node.

See http://www.w3schools.com/jsref/dom_obj_node.asp for more information on this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM