Script du jour : TinyXmlReader
Le site Bydesigngames a mis en ligne un script permettant de parser un xml externe.
Ce script très simple ne parse pas les attributs d’un xml mais l’avantage est qu’il est en javascript.
?Download TinyXmlReader.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | class TinyXmlReader { private var xmlString = ""; private var idx = 0; function TinyXmlReader(aXmlString : String) { xmlString = aXmlString; } var tagName = ""; var isOpeningTag = false; var content = ""; function Read() : boolean { idx = xmlString.IndexOf("<", idx); if (idx == -1) { return false; } ++idx; var endOfTag = xmlString.IndexOf(">", idx); if (endOfTag == -1) { return false; } tagName = xmlString.Substring(idx, endOfTag-idx); idx = endOfTag; // check if a closing tag if (tagName.StartsWith("/")) { isOpeningTag = false; tagName = tagName.Remove(0, 1); // remove the slash } else { isOpeningTag = true; } // if an opening tag, get the content if (isOpeningTag) { var startOfCloseTag = xmlString.IndexOf("<", idx); content = xmlString.Substring(idx+1, startOfCloseTag-idx-1); content = content.Trim(); } return true; } // returns false when the endingTag is encountered function Read(endingTag : String) : boolean { var retVal = Read(); if (tagName == endingTag && !isOpeningTag) { retVal = false; } return retVal; } } </javascript> ==Usage== Here I provide example code on how to use the TinyXmlReader. <javascript> private var text : String; var skin : GUISkin; function OnGUI() { GUILayout.Label(text, skin.label); } function Start() { var xmlText = System.IO.File.ReadAllText(Application.dataPath + "/Rifleman.xml"); var reader = TinyXmlReader(xmlText); while (reader.Read()) { if (reader.isOpeningTag) { text += (reader.tagName + " \"" + reader.content + "\"\n"); } if (reader.tagName == "Skills" && reader.isOpeningTag) { while(reader.Read("Skills")) // read as long as not encountering the closing tag for Skills { if (reader.isOpeningTag) { text += ("Skill: " + reader.tagName + " \"" + reader.content + "\"\n"); } } } } } |
Super Kriss, tu tombe toujours sur des codes qui vont nous faciliter la vie! Continu, ton site est un vrai mine pour nous !