3

I have an xml file that looks like this :

<Factory>
<Limits>
  <Point X="92" Y="489"/>
  <Point X="570" Y="487"/>
  <Point X="570" Y="138"/>
  <Point X="92" Y="140"/>
  <Point X="92" Y="139"/>
</Limits>
<Cells>
  <Cell>
    <Point X="358" Y="138"/>
    <Point X="361" Y="487"/>
    <Point X="570" Y="487"/>
    <Point X="570" Y="138"/>
    <Point X="358" Y="138"/>
  </Cell>
  <Cell>
    <Point X="311" Y="139"/>
    <Point X="311" Y="488"/>
    <Point X="92" Y="489"/>
    <Point X="92" Y="140"/>
    <Point X="311" Y="139"/>
  </Cell>
</Cells>

I'm trying to get the X and Y values of each "Point" in "Limits" (not those in "Cell") using Javascript. I saw a lot of examples with getElementByTagName, childNodes, ... but I can't figure out how to get the data I'm looking for. I thought something like this would work:

var M = xmlDoc.getElementsByTagName("Limits")[0].childNodes;
for (i=0;i<M.length;i++){
  console.log(M[i].childNodes.item(0));
}

I tried a few different things but I always end up either with a null value or with an error.

Is there any simple way to do what I need ?

4
  • 1
    is needs to be like this <Point>data</Point> Commented Mar 6, 2013 at 11:51
  • 1
    can you use jquery solution?? Commented Mar 6, 2013 at 11:52
  • Yes, I could use jquery. Commented Mar 6, 2013 at 12:37
  • @ubercooluk Sadly the xml is generated by another application and I can't change the way it's made. Commented Mar 6, 2013 at 12:57

2 Answers 2

3

You need to get the attributes. With javascript:

M[i].getAttribute("X");

with jQuery:

M[i].attr("X");
Sign up to request clarification or add additional context in comments.

4 Comments

Thx, getAttribute works on M[i] but not on M[i].childNodes[j]. Any idea why ?
Because there are no childNodes. M[i] is the "Point" tag, and it has no children.
Ok, thank you. Thing is now I get the "getAttribute is not a function" error (using firefox). Edit : Nvm, it is firefox related, I had to add a M[i].nodeType == 1 condition it now it works fine !
Done, except for the vote up since I need a bit more reputation.
0
var M = xmlDoc.getElementsByTagName("Limits");
for (i = 0; i < M.length; i++){
   for(var j = 0; j < M[i].childNodes.length; j++){
      console.log(M[i].childNodes[j].getAttribute('X'));
      console.log(M[i].childNodes[j].getAttribute('Y'));
   }
}

1 Comment

Thank you, but when I try this it gives me an error :TypeError: M[i].childNodes[j].getAttribute is not a function (I'm using firefox)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.