tinyxml2使用的记录

类结构

XMLNode指的是所有被<…>…</…>包括的内容, 具体有声明, 注释, 节点及节点间的文本.
例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
0. 整个文档为XMLDocument
1. 下面为XMLDeclaration
<?xml version="1.0" encoding="UTF-8"?>
2. 一个<phonebook>...</phonebook>是一个XMLElement
<phonebook>
3. XMLComment
<!--one item behalfs one contacted person.-->
4. 一个<item>是一个XMLElement;
5. item中的name="1"是一个XMLAttribute
<item name="1">
5. item中的<name>也是一个XMLElement
6. <name></name>之间的是一个XMLText
<name>miaomaio</name>
<addr>Shaanxi Xi'an</addr>
<tel>13759911917</tel>
<email>miaomiao@home.com</email>
</item>
<item name="2">
<name>gougou</name>
<addr>Liaoning Shenyang</addr>
<tel>15840330481</tel>
<email>gougou@home.com</email>
</item>
3. 下面为XMLComment
<!--more contacted persons.-->
</phonebook>

写的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
bool writexmlfile() {
try {
XMLDocument* xmldoc = new XMLDocument();

// 设置文件声明
const char* decla = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
XMLDeclaration* declarations = xmldoc->NewDeclaration(decla);
xmldoc->LinkEndChild(declarations);
// 创建根元素
XMLElement* rootele = xmldoc->NewElement("phonebook");
// 链接作为根对象
xmldoc->LinkEndChild(rootele);

// 创建一个元素
XMLElement* item1 = xmldoc->NewElement("item");
// 链接到根元素就成为根元素的第一个项
rootele->LinkEndChild(item1);
// 为第一个项设置属性
item1->SetAttribute("name", "1");
// 为item1设置俩个元素
XMLElement* name1 = xmldoc->NewElement("name");
XMLElement* tel1 = xmldoc->NewElement("tel");
item1->LinkEndChild(name1);
item1->LinkEndChild(tel1);
// 为元素设置
name1->SetText("Ding");
tel1->SetText("111111");

// 保存文件
xmldoc->SaveFile("write.xml");
} catch (...) {
return false;
}

return true;
}

读的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
bool readxmlfile() {
try {
XMLDocument* xmldoc = new XMLDocument();
xmldoc->LoadFile("write.xml");

// 读声明

// root
XMLElement* root = xmldoc->RootElement();
// item1
XMLElement* item1 = root->FirstChildElement();
XMLElement* name1 = item1->FirstChildElement();
XMLElement* tel1 = name1->NextSiblingElement();
// 得到item1的attribute属性值
const char* item1name = item1->Attribute("name");
std::cout << "item1属性值:" << item1name << std::endl;
// 得到name1和tel1的XMLText值
const char* name1val = name1->GetText();
const char* tel1val = tel1->GetText();
std::cout << "name项的值为:" << name1val << std::endl;
std::cout << "tel项的值为: " << tel1val << std::endl;

// item2
// XMLElement* item2 = item1->NextSiblingElement("item");
//
delete xmldoc;
} catch (...) {
return false;
}

return true;
}