c xml 格式化对齐

来源:互联网 发布:广州数据恢复 价格 编辑:程序博客网 时间:2024/05/23 19:12

程序使用msxml做xml读写。最后保存的时候全都混成一堆。自己写了个简单的xml缩进的函数。只能满足一些简单的格式化需要




std::string PrettyPrint( const char* strSource, const char* strN /*= "\n"*/ )
{
stack<int> stackDeep;


int iLenght = strlen(strSource);
char* strText = (char*)strSource;
char* strStart = strText;


string strXML;
int iNodeNum = 0;
bool bStop = false;


while(*strText)
{
if(*strText == '<')//起始字符
{
strStart = strText;


if(*(strText + 1) == '/')//截止的节点
{
bStop = true;
}
else //起始节点
{
iNodeNum++; //计数本层的
stackDeep.push(iNodeNum);
iNodeNum = 0; //本层次的子节点计0
bStop = false;
}
}
else if(*strText == '>')
{
if(*(strText - 1) == '/')//截止节点
{
bStop = true;
}


string strPrerry = "";
//if(bStop == false || iNodeNum > 1)//存在子节点,换行并且缩进
{
int iSize = (int)stackDeep.size();
//if(iSize > 1)
{
strPrerry += strN;
}


for (int i = 1; i < iSize; i++)
{
strPrerry += "    ";
}
}


char cTmp = strText[1];
strText[1] = 0;
strPrerry += strStart;
strText[1] = cTmp;//恢复


strXML += strPrerry;


if(bStop)
{
iNodeNum = stackDeep.top();
stackDeep.pop();
}




bStop = false;
}


++strText;
}
return strXML;
}

原创粉丝点击