使用tinyxml2生成和解析xml文档

本文介绍了如何使用tinyxml2库在C++中读取和生成XML文档。通过实例展示了从dream.xml文件中提取PLAY元素的TITLE子元素的文本内容,并探讨了XML中键值对的两种表示方式,即属性和元素文本。tinyxml2提供了相应的访问器方法QueryIntAttribute()和QueryIntText()来获取这些信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

xml文档主要用于储存数据进行配置。

tinyxml2的官方文档

https://github.com/leethomason/tinyxml2

第一步是建立一个c++文件

这里使用的是qt creatot编辑器,也可以在命令行下编译。

#include <iostream>
#include <tinyxml2.h>
using namespace tinyxml2;
using namespace std;

int main(int argc, char *argv[])
{
    XMLDocument doc;
    doc.LoadFile("dream.xml");
    // Structure of the XML file:
    // - Element "PLAY"     the root Element, which is the FirstChildElement of the Document
    // -- Element "TITLE"   child of the root PLAY Element
    // --- Text             child of the TITLE Element
    // Navigate to the title, using the convenience function
    // const char * title = doc.FirstChildElement("PLAY");
    return 0;
}

手动写一个dream.xml文件

<PLAY>
    <TITLE>A Midsummer Night's Dream</TITLE>
</PLAY>

wang@wang:~/test$ g++ parsexml.cpp -o parsexml
/tmp/ccJ1gyNX.o: In function `main':
parsexml.cpp:(.text+0x2e): undefined reference to `tinyxml2::XMLDocument::XMLDocument(bool, tinyxml2::Whitespace)'

如果值有parsexml.cpp文件的话会出现如上错误,

所以正确的编译选项

wang@wang:~/test$ g++ parsexml.cpp /home/wang/github/tinyxml2/tinyxml2.cpp -o parsexml

tinyxml2.cpp是文件的安装位置。

怎么安装tinyxml2查看上面提供的官方文档。

qt中需要配置parsexml.pro文件,加上最后一行,编译成功。

parsexml.pro

TEMPLATE = app
CONFIG += console c++11
CONFIG -= app_bundle
CONFIG -= qt

SOURCES += main.cpp

SOURCES += ~/github/tinyxml2/tinyxml2.cpp

#include <iostream>
#include <tinyxml2.h>
using namespace tinyxml2;
using namespace std;

int main(int argc, char *argv[])
{
    XMLDocument doc;
    doc.LoadFile("dream.xml");
    // Structure of the XML file:
    // - Element "PLAY"     the root Element, which is the FirstChildElement of the Document
    // -- Element "TITLE"   child of the root PLAY Element
    // --- Text             child of the TITLE Element
    // Navigate to the title, using the convenience function
    const char * title = doc.FirstChildElement("PLAY")->FirstChildElement("TITLE")->GetText();
    printf("Name of play (1): %s\n", title);

    // Text is just another Node to TinyXML-2. The more
    // general way to get to the XMLText:
    XMLText *textNode = doc.FirstChildElement("PLAY")->FirstChildElement("TITLE")->FirstChild()->ToText();
    title = textNode->Value();
    printf("Name of play (2): %s\n", title);
    return 0;
}

运行结果:

Name of play (1): A Midsummer Night's Dream
Name of play (2): A Midsummer Night's Dream


主要操作有四个:

Load an XML File
Basic XML file loading. The basic syntax to load an XML file from disk and check for an error. (ErrorID() will return 0 for no error.)
int example_1()
{
XMLDocument doc;
doc.LoadFile( "resources/dream.xml" );
return doc.ErrorID();
}

Parse an XML from char buffer
Basic XML string parsing. The basic syntax to parse an XML for a char* and check for an error. (ErrorID() will return 0 for no error.)
int example_2()
{
static const char* xml = "<element/>";
XMLDocument doc;
doc.Parse( xml );
return doc.ErrorID();
}


Get information out of XML
In this example, we navigate a simple XML file, and read some interesting text. Note that this example doesn't use error checking; working code should check for null pointers when walking an XML tree, or use XMLHandle.

(The XML is an excerpt from "dream.xml").

int example_3()
{
static const char* xml =
"<?xml version=\"1.0\"?>"
"<!DOCTYPE PLAY SYSTEM \"play.dtd\">"
"<PLAY>"
"<TITLE>A Midsummer Night's Dream</TITLE>"
"</PLAY>";

The structure of the XML file is:

  • (declaration)
  • (dtd stuff)
  • Element "PLAY"
    • Element "TITLE"
      • Text "A Midsummer Night's Dream"

For this example, we want to print out the title of the play. The text of the title (what we want) is child of the "TITLE" element which is a child of the "PLAY" element.

We want to skip the declaration and dtd, so the method FirstChildElement() is a good choice. The FirstChildElement() of the Document is the "PLAY" Element, the FirstChildElement() of the "PLAY" Element is the "TITLE" Element.

XMLDocument doc;
doc.Parse( xml );
XMLElement* titleElement = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" );

We can then use the convenience function GetText() to get the title of the play.

const char* title = titleElement->GetText();
printf( "Name of play (1): %s\n", title );

Text is just another Node in the XML DOM. And in fact you should be a little cautious with it, as text nodes can contain elements.

Consider: A Midsummer Night's <b>Dream</b>

It is more correct to actually query the Text Node if in doubt:

XMLText* textNode = titleElement->FirstChild()->ToText();
title = textNode->Value();
printf( "Name of play (2): %s\n", title );

Noting that here we use FirstChild() since we are looking for XMLText, not an element, and ToText() is a cast from a Node to a XMLText.


Read attributes and text information.

There are fundamentally 2 ways of writing a key-value pair into an XML file. (Something that's always annoyed me about XML.) Either by using attributes, or by writing the key name into an element and the value into the text node wrapped by the element. Both approaches are illustrated in this example, which shows two ways to encode the value "2" into the key "v":

bool example_4()
{
static const char* xml =
"<information>"
" <attributeApproach v='2' />"
" <textApproach>"
" <v>2</v>"
" </textApproach>"
"</information>";

TinyXML-2 has accessors for both approaches.

When using an attribute, you navigate to the XMLElement with that attribute and use the QueryIntAttribute() group of methods. (Also QueryFloatAttribute(), etc.)

XMLElement* attributeApproachElement = doc.FirstChildElement()->FirstChildElement( "attributeApproach" );
attributeApproachElement->QueryIntAttribute( "v", &v0 );

When using the text approach, you need to navigate down one more step to the XMLElement that contains the text. Note the extra FirstChildElement( "v" ) in the code below. The value of the text can then be safely queried with the QueryIntText() group of methods. (Also QueryFloatText(), etc.)

XMLElement* textApproachElement = doc.FirstChildElement()->FirstChildElement( "textApproach" );
textApproachElement->FirstChildElement( "v" )->QueryIntText( &v1 );


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值