Manipulating XML with Javascript

Asked

Viewed 1,188 times

0

I’m having a doubt and I’ve searched a lot and I still can’t solve.

I have an XML with a tag called <child id='minhatag'/>. I need to make javascript to read this tag and be able to return the Child tag ID value so that the value I can put on a button, because my screen will have several buttons that will be displayed according to the values of "Child’s ID’s". NOTE: Remember that there will be several Children for example:

<child id='child1'/>
<child id='child2'/>
<child id='child3'/>

And XML will be in the same folder structure of the code or will not be an access via URL, at least not at first.

  • This is along with the HTML? elements is an AJAX result?

  • But what is the value of child?

  • @Guilherme Lautert not the values in CHILD are in a separate file.

  • @Magichat to Child does not have a value itself I need to have the return of Child ID value.

2 answers

1


You can use the code below to do this, but you need a father to sew the parse:

var xml, parser, xmlDoc;
text = "<children><child id='child1'/>" +
       "<child id='child2'/>" +
       "<child id='child3'/></children>";

parser = new DOMParser();
xmlDoc = parser.parseFromString(text, "text/xml");
xmlDoc.getElementsByTagName("children")[0].childNodes.forEach(function(value) {
    console.log(value.id);
});

  • but how would you do in the case to access an xml that is in a file of it, because that way that you presented it is pulling fixed items inside the script itself in the right index ? It would be as if it were in an XML called "Child.xml" for example and all the code would be there.

  • I even forgot to comment they have a father, in case the <Children><Child id="child1" /></Children> basically

  • No problem, just change the father selector from Childs to Children. It was up to a fault of my English rs

  • and as for the access part to an xml file and not within the script structure itself in js ?

  • Here is a question with a great answer to help. Since the focus of this question was not how to read from a file: https://stackoverflow.com/questions/14446447/javascript-read-local-text-file

  • thanks with your answer I got a satisfactory result for question, I will open another question to another problem that arose. Thank you.

Show 1 more comment

0

Kind of:

var childs = document.getElementsByTagName("child");
for (var i = 0; i < childs.length; i++) {
  console.log(childs[i].id);
}
    <child id='child1'/>
    <child id='child2'/>
    <child id='child3'/>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.