TinyXML与lua的绑定及使用
TinyXML
For Lua 5.0:
From: Robert Noll
Just a plain "Parse File to lua array" function in c++, using the [TinyXML] (2.4.3) lib.
-
// header class lua_State; /// register parser functions to lua void RegisterLuaXML (lua_State *L); // sourcefile #include "tinyxml.h" extern "C" { #include "lua.h" #include "lauxlib.h" #include "lualib.h" } void LuaXML_ParseNode (lua_State *L,TiXmlNode* pNode) { PROFILE if (!pNode) return; // resize stack if neccessary luaL_checkstack(L, 5, "LuaXML_ParseNode : recursion too deep"); TiXmlElement* pElem = pNode->ToElement(); if (pElem) { // element name lua_pushstring(L,"name"); lua_pushstring(L,pElem->Value()); lua_settable(L,-3); // parse attributes TiXmlAttribute* pAttr = pElem->FirstAttribute(); if (pAttr) { lua_pushstring(L,"attr"); lua_newtable(L); for (;pAttr;pAttr = pAttr->Next()) { lua_pushstring(L,pAttr->Name()); lua_pushstring(L,pAttr->Value()); lua_settable(L,-3); } lua_settable(L,-3); } } // children TiXmlNode *pChild = pNode->FirstChild(); if (pChild) { int iChildCount = 0; for(;pChild;pChild = pChild->NextSibling()) { switch (pChild->Type()) { case TiXmlNode::DOCUMENT: break; case TiXmlNode::ELEMENT: // normal element, parse recursive lua_newtable(L); LuaXML_ParseNode(L,pChild); lua_rawseti(L,-2,++iChildCount); break; case TiXmlNode::COMMENT: break; case TiXmlNode::TEXT: // plaintext, push raw lua_pushstring(L,pChild->Value()); lua_rawseti(L,-2,++iChildCount); break; case TiXmlNode::DECLARATION: break; case TiXmlNode::UNKNOWN: break; }; } lua_pushstring(L,"n"); lua_pushnumber(L,iChildCount); lua_settable(L,-3); } } static int LuaXML_ParseFile (lua_State *L) { PROFILE const char* sFileName = luaL_checkstring(L,1); TiXmlDocument doc(sFileName); doc.LoadFile(); lua_newtable(L); LuaXML_ParseNode(L,&doc); return 1; } void RegisterLuaXML (lua_State *L) { lua_register(L,"LuaXML_ParseFile",LuaXML_ParseFile); }
1.RegisterLuaXML 注册一个函数到lua函数映射表中
2.lua中调用LuaXML_ParserFile来解析xml表格
3.lua_settable(L,-3)弹出key、value,设置到table中。
lua中使用方法:
1.在Lua中直接写明 LuaXML_ParseFile("xx/xx/xx.xml")就可以了。
2."xx/xx/xx.xml"会被压入栈的顶端,同时LuaXML_ParseFile中调用luaL_checkstring(L,1)即可获得字符串.
3.LuaXML_ParseFile直接返回一个解析好的table