前言
本文使用tinystr.cpp、tinyxml.cpp
来进行对xml的读写操作;
创建与读取xml
创建xml
const char* demoStart =
"<?xml version=\"1.0\" standalone='no' >\n"
"<!-- Our to do list data -->"
"<ToDo>\n"
"<!-- Do I need a secure PDA? -->\n"
"<Item priority=\"1\" distance='close'> Go to the <bold>Toy store!</bold></Item>"
"<Item priority=\"2\" distance='none'> Do bills </Item>"
"<Item priority=\"2\" distance='far & back'> Look for Evil Dinosaurs! </Item>"
"</ToDo>";
TiXmlDocument Doc("demotest.xml");
Doc.Parse(demoStart);
if (Doc.Error())
{
printf("Error in %s: %s\n", Doc.Value(), Doc.ErrorDesc());
exit(1);
}
Doc.SaveFile();
读取xml
TiXmlDocument doc("demotest.xml");
bool loadOkay = doc.LoadFile();
if (!loadOkay)
{
printf("Could not load test file 'demotest.xml'. Error='%s'. Exiting.\n", doc.ErrorDesc());
exit(1);
}
printf("** Demo doc read from disk: ** \n\n");
printf("** Printing via doc.Print **\n");
doc.Print(stdout);
对节点进行操作
获取根节点
此时,若有众多根节点,则取第一个根节点;
const TiXmlElement* element = doc.RootElement();
获取指定名根节点
从众多根节点中,查找名为ToDo的根节点;
TiXmlNode* node = 0;
TiXmlElement* todoElement = 0;
node = doc.FirstChild("ToDo");
assert(node);
todoElement = node->ToElement();
assert(todoElement);
获取父节点下第一个子节点
node = todoElement->FirstChildElement();
assert(node);
itemElement = node->ToElement();
assert(itemElement);
获取父节点下第二个子节点
itemElement = itemElement->NextSiblingElement();
assert(itemElement);
更改或添加所在节点的属性
若没有改属性,则会添加上去;
itemElement->SetAttribute("distance", "here");
获取节点所包含的值
element->GetText();
添加节点
// Add some meetings.
TiXmlElement item( "Item" );
item.SetAttribute( "priority", "1" );
item.SetAttribute( "distance", "far" );
TiXmlText text( "Talk to:" );
TiXmlElement meeting1( "Meeting" );
meeting1.SetAttribute( "where", "School" );
TiXmlElement meeting2( "Meeting" );
meeting2.SetAttribute( "where", "Lunch" );
TiXmlElement attendee1( "Attendee" );
attendee1.SetAttribute( "name", "Marple" );
attendee1.SetAttribute( "position", "teacher" );
TiXmlElement attendee2( "Attendee" );
attendee2.SetAttribute( "name", "Voel" );
attendee2.SetAttribute( "position", "counselor" );
// Assemble the nodes we've created:
meeting1.InsertEndChild( attendee1 );
meeting1.InsertEndChild( attendee2 );
item.InsertEndChild( text );
item.InsertEndChild( meeting1 );
item.InsertEndChild( meeting2 );
// And add the node to the existing list after the first child.
node = todoElement->FirstChild( "Item" );
assert( node );
itemElement = node->ToElement();
assert( itemElement );
todoElement->InsertAfterChild( itemElement, item );