1. 程式人生 > >c xml 格式化對齊

c xml 格式化對齊

程式使用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;
}