昨天根据TinyXML的docs,学习了一些基本的用法。TinyXML相对于Xerces来说,接口更加简洁,好理解。虽然MS XML Parser也不错,但对于需要跨平台部署的应用程序,是不适合的。
CString strMsg;
TiXmlDocument doc("demotest.xml");
bool loadOK = doc.LoadFile();
if (!loadOK)
strMsg.Format("Could not Load. [%s]\n", doc.ErrorDesc());
else
strMsg.Format("OK\n");
TiXmlHandle sectHandle(&doc);
// 修改第2个Item节点的TEXT值
sectHandle.ChildElement("ToDo", 0).ChildElement("Item", 1).Child(0).Text()->SetValue("Some Value");
// 修改的3个Item节点的distance属性
sectHandle.ChildElement("ToDo", 0).ChildElement("Item", 2).Element()->SetAttribute("distance", "so near");
// 修改第1个Item节点的名字
sectHandle.ChildElement("ToDo", 0).ChildElement("Item", 0).Element()->SetValue("Other Item");// 取得第1个Item节点的TEXT值
strMsg.Format("%s", sectHandle.ChildElement("ToDo", 0).ChildElement("Other Item", 0).Element()->GetText());
// 取得第2个Item的节点名字
strMsg.Format("%s", sectHandle.ChildElement("ToDo", 0).ChildElement("Item", 1).Element()->Value());
// 取得第3个Item节点的distance属性
strMsg.Format("%s", sectHandle.ChildElement("ToDo", 0).ChildElement("Item", 2).Element()->Attribute("distance");
// 取得第3个Item节点的priority属性
int n=0;
sectHandle.ChildElement("ToDo", 0).ChildElement("Item", 2).Element()->Attribute("priority", &n);AfxMessageBox(strMsg, MB_OK, 0);
doc.SaveFile();
XML文件的结构:
<?xml version=”1.0″ standalone=”no” ?>
<!– Our to do list data –>
<ToDo>
<!– Do I need a secure PDA? –>
<Item priority=”1″ distance=”close”>Go to the
<bold>Toy store!</bold>
</Item>
<Item priority=”2″ distance=”none”>test</Item>
<Item priority=”2″ distance=”far & back”>Look for Evil Dinosaurs!</Item>
</ToDo>


