Googled around, but most of the methods seem overly complicated, using libraries etc.
There’s not an easy way to turn a basic XML file into an array in JS?
XML file looks something like this:
<goods> <unit id="4325" loc1="2hrs" loc2="4hrs" loc3="12hrs" desc="Container 4325" /> <unit id="4326" loc1="2.5hrs" loc2="5hrs" loc3="12hrs" desc="Container 4326" /> </goods>
Do you just need the xml parser for like a textbox, or are you trying to read a local/remote file?
if you use jQuery, its really easy:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="http://www.google.com/jsapi"></script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Untitled Document</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript"> $(function() { function parseXml(xml) { $(xml).find("unit").each(function() { var xmlUnit = $(this); var retStr = ''; retStr = retStr+ "id: "+xmlUnit.attr("id")+"n"; retStr = retStr+ "loc1: "+xmlUnit.attr("loc1")+"n"; retStr = retStr+ "loc2: "+xmlUnit.attr("loc2")+"n"; retStr = retStr+ "loc3: "+xmlUnit.attr("loc3")+"n"; retStr = retStr+ "desc: "+xmlUnit.attr("desc")+"n"; alert(retStr); }); } $("#btnParse").click(function() { parseXml($("#theXml").val()); }); }); </script> <style type="text/css"> #content { width: 600px; margin: 0 auto; text-align: center; } #theXml { width: 550px; height: 550px; } </style> </head> <body> <div id="content"> <form id="xmlForm" name="xmlForm" action=""> <p><textarea id="theXml" name="theXml"></textarea></p> <p><input type="button" name="btnParse" id="btnParse" value=" Parse XML " /></p> </form> </div> </body> </html>
Googled around, but most of the methods seem overly complicated, using libraries etc.
… |
"overly complicated" and "using libraries" don’t really go together. Libraries exist to solve complicated, common problems…like this one! Try the library noon suggested, it’s a popular one.
Easiest way might to convert the XML into a JSON object
JSON is a javascript Array