Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...