| 1 | /** |
|---|
| 2 | * Parse XML file and return a simple, associative array. |
|---|
| 3 | * |
|---|
| 4 | * @author Jeroen Wijering |
|---|
| 5 | * @version 1.2 |
|---|
| 6 | **/ |
|---|
| 7 | |
|---|
| 8 | |
|---|
| 9 | class com.jeroenwijering.utils.XMLParser { |
|---|
| 10 | |
|---|
| 11 | |
|---|
| 12 | /** Flash XML object the file is loaded into. **/ |
|---|
| 13 | private var input:XML; |
|---|
| 14 | /** The object the XML is parsed into **/ |
|---|
| 15 | private var output:Object; |
|---|
| 16 | |
|---|
| 17 | |
|---|
| 18 | /** Constructor, sets up XML object **/ |
|---|
| 19 | function XMLParser() {}; |
|---|
| 20 | |
|---|
| 21 | |
|---|
| 22 | /** Start parsing **/ |
|---|
| 23 | public function parse(lnk:String) { |
|---|
| 24 | var ref = this; |
|---|
| 25 | input = new XML(); |
|---|
| 26 | output = new Object(); |
|---|
| 27 | input.ignoreWhite = true; |
|---|
| 28 | input.onLoad = function(scs:Boolean) { |
|---|
| 29 | if(scs) { |
|---|
| 30 | ref.processRoot(); |
|---|
| 31 | } else { |
|---|
| 32 | ref.onError(); |
|---|
| 33 | } |
|---|
| 34 | }; |
|---|
| 35 | if(_root._url.indexOf("file://") > -1) { |
|---|
| 36 | input.load(lnk); |
|---|
| 37 | } else if(lnk.indexOf('?') > -1) { |
|---|
| 38 | input.load(lnk+'&'+random(999)); |
|---|
| 39 | } else { |
|---|
| 40 | input.load(lnk+'?'+random(999)); |
|---|
| 41 | } |
|---|
| 42 | }; |
|---|
| 43 | |
|---|
| 44 | |
|---|
| 45 | /** Process the root XML node **/ |
|---|
| 46 | private function processRoot() { |
|---|
| 47 | processNode(input.firstChild,output); |
|---|
| 48 | delete input; |
|---|
| 49 | onComplete(output); |
|---|
| 50 | }; |
|---|
| 51 | |
|---|
| 52 | |
|---|
| 53 | /** Process a specific node **/ |
|---|
| 54 | private function processNode(nod:XMLNode,obj:Object) { |
|---|
| 55 | obj['name'] = nod.nodeName; |
|---|
| 56 | for(var att in nod.attributes) { |
|---|
| 57 | obj[att] = nod.attributes[att]; |
|---|
| 58 | } |
|---|
| 59 | if(nod.childNodes.length < 2 && nod.firstChild.nodeName == null) { |
|---|
| 60 | obj['value'] = nod.firstChild.nodeValue; |
|---|
| 61 | } else { |
|---|
| 62 | obj['childs'] = new Array(); |
|---|
| 63 | var chn = nod.firstChild; |
|---|
| 64 | var i = 0; |
|---|
| 65 | while(chn != undefined) { |
|---|
| 66 | var cob = new Object(); |
|---|
| 67 | processNode(chn,cob); |
|---|
| 68 | obj['childs'].push(cob); |
|---|
| 69 | chn = chn.nextSibling; |
|---|
| 70 | i++; |
|---|
| 71 | } |
|---|
| 72 | } |
|---|
| 73 | }; |
|---|
| 74 | |
|---|
| 75 | |
|---|
| 76 | /** Invoked when parsing is completed. **/ |
|---|
| 77 | public function onComplete(obj:Object) {}; |
|---|
| 78 | |
|---|
| 79 | |
|---|
| 80 | /** Invoked when parsing is completed. **/ |
|---|
| 81 | public function onError() {}; |
|---|
| 82 | |
|---|
| 83 | |
|---|
| 84 | } |
|---|