使用LayaAir解析xml文件


LayaBox對XML的加載進行了封裝,相對於純JS加載xmldom來說要方便了很多,我們直接調用laya的loader便可加載完成

var _res = [
    {url: "res/config/test.xml", type: laya.net.Loader.XML},
];

var loadXml = function(){
    //解析xml代碼
}

Laya.loader.load(_res, laya.utils.Handler.create(this, function () {
            //加載完畢
            loadXml();
        }));
}

注意:加載文件的類型一定要是laya.net.Loader.XML

以下是用來測試的xml

<Root Name="test">
    <ATTR1 num="0" count="147"></ATTR1>
    <ATTR2 path="test/1024.jpg" name="你猜"></ATTR2>
    <REPEATED name="小明" age="10"></REPEATED>
    <REPEATED name="李狗蛋兒" age="20"></REPEATED>
</Root>

加載完成之后就是對xml文件的解析了,首先我們要獲取這個xmldom

var xmlDom = laya.net.Loader.getRes("res/config/test.xml");

然后就可以逐層遍歷xml,把數據按我們想要的格式存儲起來

var attr = xmlDom.childNodes[0].childNodes;
for (var i = 0; i < attr.length; i++){
    if (attr[i].nodeName == "ATTR1"){
        for (var j = 0 ; j < attr[i].attributes.length ; j++){
            if (attr[i].attributes[j].nodeName == "num"){
                this._battleData.num = attr[i].attributes[j].nodeValue;
            }
            else if (attr[i].attributes[j].nodeName == "count"){
                this._battleData.count = attr[i].attributes[j].nodeValue;
            }
        }
    }
}

對於嵌套層次更深的節點,也是類似的做法 這里只是簡單地記錄一下使用方法,真正的游戲中需要把xml解析使用單獨文件來管理


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM