使用wxWidgets读取Xml文件的配置文件,通过匹配每一层结点得到指定元素属性值

#include <wx/wx.h>
#include <wx/xml/xml.h>
#include "gtest/gtest.h"

typedef struct
{
	int x;
	int y;
	int width;
	int height;
} ControlRect;


//1.每一层的名字要和元素名字要一样.
//2.如果该层元素不等于该层名字,检查下一节点.
bool GetControlRect(wxXmlNode *node, wxArrayString elementNames,
		ControlRect *rect, int level, const int max_level)
{
	while (node)
	{
		if (node->GetName() == elementNames[level])
		{
			if (level == max_level-1)
			{
				rect->x = atoi(node->GetAttribute("x", wxEmptyString));
				rect->y = atoi(node->GetAttribute("y", wxEmptyString));
				rect->width = atoi(node->GetAttribute("width", wxEmptyString));
				rect->height = atoi(
						node->GetAttribute("height", wxEmptyString));
				return true;
			}
			return GetControlRect(node->GetChildren(), elementNames, rect,
								level + 1, max_level-1);
		}
		node = node->GetNext();
	}
	return false;
}

TEST(test, GetControlRect1)
{
	wxXmlDocument doc;
	if (!doc.Load("resources/test.xml"))
	{
		return ;
	}
	wxXmlNode *child = doc.GetRoot()->GetChildren();

	ControlRect *name = (ControlRect*) malloc(sizeof(ControlRect));

	wxString piece_name = wxT("test1:test2");
	wxArrayString arr = wxSplit(piece_name, wxT(':'), NULL);

	if (GetControlRect(child, arr, name, 0, arr.size()))
	{
		ASSERT_EQ(0, name->x);
		ASSERT_EQ(0, name->y);
		ASSERT_EQ(10, name->width);
		ASSERT_EQ(5, name->height);
	}

	free(name);
}

TEST(test, GetControlRect2)
{
	wxXmlDocument doc;
	if (!doc.Load("resources/test.xml"))
	{
		return ;
	}
	wxXmlNode *child = doc.GetRoot()->GetChildren();

	ControlRect *name = (ControlRect*) malloc(sizeof(ControlRect));

	wxString piece_name = wxT("test1:test2:test3");
	wxArrayString arr = wxSplit(piece_name, wxT(':'), NULL);

	if (GetControlRect(child, arr, name, 0, arr.size()))
	{
		ASSERT_EQ(508, name->x);
		ASSERT_EQ(54, name->y);
		ASSERT_EQ(244, name->width);
		ASSERT_EQ(236, name->height);
	}

	free(name);
}

int main(int argc, char* argv[])
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}


 

你可能感兴趣的:(使用wxWidgets读取Xml文件的配置文件,通过匹配每一层结点得到指定元素属性值)