1

Trying to load and parse some XML data:

<image name='image1' xsize='200' ysize='100'>
  <solidcolor startxy='0,0' endxy='50,75' color='0072ff'>
    <text startxy='50,50' endxy='150,70' color='000000' size='12'>text to print</text>
</image>
<image name='image2' xsize='200' ysize='100'>
  <img src='background.jpg' startxy='0,0' endxy='200,100'>
  <text startxy='50,50' endxy='150,70' color='000000' size='12'>text to print</text>
  <text startxy='0,0' endxy='150,20' color='000000' size='12'></text>
</image>

The code below works, kind of, but I'm unable to get all the data like 'name', 'xsize', or any of the other data from between the <>. Also if there is nothing between the tags it will crash and if there is no closing tag it will crash. I'm new to JavaScript but HTML can do all this so I assume JavaScript can as well?

var x, i, xmlDoc;
var txt = "";
var text = "<book>" +
  "<title size='1'>Everyday Italian</title>" +
  "<text style='1'></text>" +
  "<author>Giada De Laurentiis</author>" +
  "<year>2005</year>" +
  "</book>";

parser = new DOMParser();
xmlDoc = parser.parseFromString(text, "text/xml");

// documentElement always represents the root node
x = xmlDoc.documentElement.childNodes;
for (i = 0; i < x.length; i++) {
  txt += x[i].nodeName + ": " + x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;
<p id="demo"></p>

3
  • 1
    Your XML is incorrectly formed. I'd suggest you either use a XML editor to verify it or use Json for a modern approach. Commented May 30, 2018 at 19:45
  • The data like "name", "xsize", etc. are called "attributes", so you'll want to iterate over those as well. Commented May 30, 2018 at 19:50
  • Possible duplicate of Parsing xml in Javascript iterate through child nodes Commented May 30, 2018 at 19:52

1 Answer 1

1

You can access attributes on the node via the attributes property:

Example:

xmlDoc.documentElement.childNodes[1].attributes.style.value

This would give you "1"

Experiment in the chrome console and inspect what properties are available.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.