python之自动生成解析xml的C++类

##xml2parser.py

import os,sys,re
from string import Template

gHearFile = "cmd_parser"
gSrcFile = "cmd_parser"
gClassName = "CCParseXml"

class CObject(object):
    #@Consist
    def __init__(self):
        self._content = ""
        self._rootTag = ""
        self._subList = []
        self._gMap = {}
    #@Setter
    def setContent(self,content):
        self._content = content;
    def setRootTage(self,root):
        self._rootTag = root
    def addSubTag(self,subTag,value):
        self._subList.append(subTag)
        self._gMap[subTag] = value
    #@To
    def to_Def_List(self):
        ret = ""
        for tag in self._subList:
            s1 = "\tTiXmlNode * %s_Node;\n" % (tag)
            ret += s1
        return ret
    def to_Init_List(self):
        ret = ""
        for tag in self._subList:
            s1 = "\t%s_Node = NULL;\n" % (tag)
            ret += s1
        return ret
    def to_parse_subTags(self):
        nOrder = 1
        prefix = ""
        ret = ""
        for tag in self._subList:
            if (nOrder == 1):
                prefix = "\t\tif"
                nOrder += 1
            else:
                prefix = "\t\telse if"
            s1 = '%s( child->Type() == TiXmlNode::ELEMENT && !strcmp(child->Value(),"%s")){\n' % (prefix,tag)
            s1 += '\t\t\t%s_Node = (TiXmlNode *)child->FirstChild();\n' % (tag)
            s1 += '\t\t\tif(%s_Node != NULL && %s_Node->Value() != NULL)\n' % (tag,tag)
            s1 += '\t\t\t{\n'
            xVal = self._gMap[tag].strip()
            if re.match("\D",xVal):
                s1 += "\t\t\t\tstrcpy(msg->%s,%s_Node->Value());\n" % (tag,tag)
            else:
                value = "atoi(%s_Node->Value())" % (tag)
                s1 += '\t\t\t\tmsg->%s = %s;\n' % (tag ,value)
            s1 += '\t\t\t}\n'
            s1 += '\t\t}\n'
            ret += s1
        return ret

###########################################################################
#   write string to file.
###########################################################################
def writeToFile(str,fname):
    fp = open(fname,"w+")
    fp.write(str)
    fp.close()

###########################################################################
#   generate the header file.
###########################################################################
def saveHeadFile(varList):
    m_hContent = Template(
"""/******************************************************************************
@fileName    : ${FILE_NAME}.h
@description : define for the ${CLASS_NAME} class
******************************************************************************/
#ifndef ${FILE_NAME_UP}_H
#define ${FILE_NAME_UP}_H

#include "typedef.h"
#include "tinyxml.h"

class ${CLASS_NAME}
{
public:
    ${CLASS_NAME}(){}
    INT32 parseToMessage(PCHAR pXmlMsg ,Message * msg);
private:
    TiXmlDocument doc;
    iXmlElement *rootElem;
${VAR_LIST}};
#endif""")
    h_str = m_hContent.substitute(FILE_NAME = gHearFile,
                                  FILE_NAME_UP = gHearFile.upper(),
                                  CLASS_NAME = gClassName,
                                  VAR_LIST = varList)
    writeToFile(h_str,gHearFile + ".h")
    
###################################################################################################
#[OK]   generate the soruce file.
###################################################################################################
def saveBodyFile(varInitList,varParseList):
    m_bContent = Template(
"""/******************************************************************************
*
*  File name : ${FILE_NAME}.cpp
*  Title     : Implementation of the ${CLASS_NAME} class
*
******************************************************************************/
#include "${FILE_NAME}.h"
#include <string.h>

/******************************************************************************
*   @pXmlMsg    :   XML Content.
*   @msg        :   Store the Parsed Xml Result.
*   @Return     :   0 (OK) ,-1 (Fail)
******************************************************************************/
INT32 CCParseXml::parseToMessage(PCHAR pXmlMsg ,Message * msg){
    if(pXmlMsg == NULL || strlen(pXmlMsg) <= 0)
        return -1;
    if(rcvMsgSt == NULL)
        return -1;

${VAR_INIT_LIST}
    doc.Parse(pXmlMsg);
    rootElem = doc.RootElement();
    if(!rootElem){
        return -1;
    }
    for( const TiXmlNode* child = rootElem->FirstChild();child;child=child->NextSibling() ){
${VAR_PARSE_LIST}\t}
    return 0;
}
""")
    b_str = m_bContent.substitute(FILE_NAME=gSrcFile,
                                  CLASS_NAME=gClassName,
                                  VAR_INIT_LIST=varInitList,
                                  VAR_PARSE_LIST=varParseList)
    writeToFile(b_str,gSrcFile + ".cpp")

###################################################################################################
#[OK]   parse the xml
###################################################################################################
gObj = CObject()
def doParse(xml):
    global gObj
    cntList =open(xml,'r+').readlines()
    print "\n########################################################"
    for cnt in cntList:
        m = re.match(r'\s*<([^/><?]+)>\s*\n',cnt)
        if m:
            print "Root:\t%s" % (m.group(1))
            gObj.setRootTage(m.group(1))
            continue
        m = re.match(r'\s*<([^/><]+)>([^><]+)</([^/><]+)>',cnt)
        if m:
            print "Node:\t%s\t-> %s" % (m.group(1),m.group(2))
            gObj.addSubTag(m.group(1),m.group(2))
            continue
    print "########################################################"

###################################################################################################
#[OK]   The Main Logic
###################################################################################################
if len(sys.argv) < 2:
    print "Usage:\tdev.py test.xml"
else:
    doParse(sys.argv[1])
    vDefList = gObj.to_Def_List()
    vInitList = gObj.to_Init_List()
    vParseList = gObj.to_parse_subTags()
    saveHeadFile(vDefList)
    saveBodyFile(vInitList,vParseList)


##用法##
xml2parser.py person.xml

阅读更多
个人分类: Python
上一篇python之string操作汇总
下一篇python之WebSocket的开发
想对作者说点什么? 我来说一句

C++ 解析xml类 tinyXML

2013年01月05日 1.96MB 下载

Xml文件自动生成C# Class类

2016年04月11日 335KB 下载

Cmarkup类....

2014年05月04日 45KB 下载

c++实现解析xml

2017年07月31日 8.91MB 下载

没有更多推荐了,返回首页

关闭
关闭