iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > 其他教程 >C++使用TinyXML解析XML
  • 876
分享到

C++使用TinyXML解析XML

2024-04-02 19:04:59 876人浏览 安东尼
摘要

目录1.介绍2.TinyXML配置3.TinyXML读取和保存文件3.1 读取xml文件3.2 读取xml参数3.3 保存xml参数到文本3.4 保存xml参数到临时变量4.Tiny

1.介绍

Tinyxml的官方网址:Http://www.grinninglizard.com

官方介绍文档:http://www.grinninglizard.com/tinyxmldocs/tutorial0.html

在TinyXML中,根据XML的各种元素来定义了一些类:

  • TiXmlBase:整个TinyXML模型的基类。
  • TiXmlAttribute:对应于XML中的元素的属性。
  • TiXmlnode:对应于DOM结构中的节点。
  • TiXmlComment:对应于XML中的注释
  • TiXmlDeclaration:对应于XML中的申明部分,即<?versiong="1.0" ?>。
  • TiXmlDocument:对应于XML的整个文档。
  • TiXmlElement:对应于XML的元素。
  • TiXmlText:对应于XML的文字部分
  • TiXmlUnknown:对应于XML的未知部分。
  • TiXmlHandler:定义了针对XML的一些操作。

根据下图来说明常用的类对应的文本格式:


<?xml version="1.0" ?> //TiXmlDeclaration,声明
<MyApp>    //TiXmlElement,元素
    <!-- Settings for MyApp -->//TiXmlComment,注释
    <Messages>//TiXmlElement,元素
        <Welcome>Welcome to MyApp</Welcome>
//<Welcome>是元素TiXmlElement ,“Welcome to MyApp”是TiXmlText,文本
        <Farewell>Thank you for using MyApp</Farewell>//同上
    </Messages>
    <windows>//TiXmlElement,元素
        <Window name="MainFrame" x="5" y="15" w="400" h="250" />
// Window是元素TiXmlElement ,name、x、y、h是TiXmlAttribute
    </Windows>
    <Connection ip="192.168.0.1" timeout="123.456000" />
</MyApp>

TinyXML是个解析库,主要由DOM模型类(TiXmlBase、TiXmlNode、TiXmlAttribute、TiXmlComment、TiXmlDeclaration、TiXmlElement、TiXmlText、TiXmlUnknown)和操作类(TiXmlHandler)构成。它由两个头文件(.h文件)和四个CPP文件(.cpp文件)构成,用的时候,只要将(tinyxml.h、tinystr.h、tinystr.cpp、tinyxml.cpp、tinyxmlerror.cpp、tinyxmlparser.cpp)导入工程就可以用它的东西了。如果需要,可以将它做成自己的DLL来调用。

注意,TiXmlBase 是TiXmlNode的基类,TiXmlNode是TiXmlElement、TiXmlComment、TiXmlText、TiXmlDeclaration、TiXmlUnknown、TiXmlDocument的基类。

2.TinyXML配置

在stdafx.h头文件中增加头文件引用#include "tinyxml/tinyxml.h"

在工程设置中加入lib引用库

在stdafx.h中加入动态库引用


#ifdef _DEBUG
#pragma comment(lib,"TinyXMLD.lib")
#else
#pragma comment(lib,"TinyXML.lib")
#endif

3.TinyXML读取和保存文件

3.1 读取xml文件


TiXmlDocument lconfigXML;
if( !lconfigXML.LoadFile( strXmlFile.c_str() ) )
{
    break;
}

3.2 读取xml参数


TiXmlDocument lActionXML;
lActionXML.Parse(strRmcpParam.c_str());
if(lActionXML.Error())
{
     strErr = "输入参数不是标准的xml格式";
     return false;
 }

3.3 保存xml参数到文本


TiXmlDocument tyDoc;
…
tyDoc.SaveFile(m_strFilePath);

3.4 保存xml参数到临时变量


TiXmlDocument tyDoc;
…
TiXmlPrinter printer;
tyDoc.Accept(&printer);
std::string devParam = std::string(printer.CStr());

4.TinyXML增删改查

4.1 增

创建一个如1中的xml文件代码


void write_app_settings_doc( )  
{  
    TiXmlDocument doc;  
    TiXmlElement* msg;
     TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );  
    doc.LinkEndChild( decl );   
    TiXmlElement * root = new TiXmlElement( "MyApp" );  
    doc.LinkEndChild( root );  
    TiXmlComment * comment = new TiXmlComment();
    comment->SetValue(" Settings for MyApp " );  
    root->LinkEndChild( comment );   
    TiXmlElement * msgs = new TiXmlElement( "Messages" );  
    root->LinkEndChild( msgs );   
    msg = new TiXmlElement( "Welcome" );  
    msg->LinkEndChild( new TiXmlText( "Welcome to MyApp" ));  
    msgs->LinkEndChild( msg );   
    msg = new TiXmlElement( "Farewell" );  
    msg->LinkEndChild( new TiXmlText( "Thank you for using MyApp" ));  
    msgs->LinkEndChild( msg );   
    TiXmlElement * windows = new TiXmlElement( "Windows" );  
    root->LinkEndChild( windows );  
    TiXmlElement * window;
    window = new TiXmlElement( "Window" );  
    windows->LinkEndChild( window );  
    window->SetAttribute("name", "MainFrame");
    window->SetAttribute("x", 5);
    window->SetAttribute("y", 15);
    window->SetAttribute("w", 400);
    window->SetAttribute("h", 250);
    TiXmlElement * cxn = new TiXmlElement( "Connection" );  
    root->LinkEndChild( cxn );  
    cxn->SetAttribute("ip", "192.168.0.1");
    cxn->SetDoubleAttribute("timeout", 123.456); // floating point attrib
    dump_to_stdout( &doc );
    doc.SaveFile( "appsettings.xml" );  
} 

在节点最后插入新节点


TiXmlNode* LinkEndChild( TiXmlNode* addThis );

在节点后 前/后 插入新节点


TiXmlNode* InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis );
TiXmlNode* InsertAfterChild(  TiXmlNode* afterThis, const TiXmlNode& addThis );

4.2 删

删除某个节点, TiXmlNode是TiXmlElement、TiXmlComment、TiXmlText、TiXmlDeclaration、TiXmlUnknown、TiXmlDocument的基类


TiXmlNode node;
node.Clear();

从A节点上移除子节点B


TiXmlNode nodeA;
nodeA. RemoveChild( TiXmlNode* removeThis );

从元素A上移除名字为B的属性


TiXmlAttribute attrA;
attrA. RemoveAttribute( const char * name );

4.3 改

查找内容为<mfid val="1234" />,现需要将1234改成其他值


TiXmlNode* lpnode = NULL;
lpnode = tixml.RootElement()->IterateChildren("mfid",lpnode);
TiXmlAttribute* tiattr = lpnode->ToElement()->FirstAttribute();
//找到mfid节点,获取第一个属性值。注意,如果有多个属性值,需要判断哪个属性值是需要的
tiattr->SetValue(mfid.c_str());

替换一个节点


TiXmlNode* ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ); 

4.4 查

获取link节点


const TiXmlNode* lpItemNode = NULL;//初始化
lpItemNode = lconfigXML.RootElement()->IterateChildren("link", lpItemNode);
if (lpItemNode == NULL)
{
    //Can not find <link>break;
}

获取link节点中的type属性值


std::string strType = lpItemNode->ToElement()->Attribute("type");

遍历节点


const TiXmlNode* lpMapNode = NULL; //初始化
lpMapNode = lconfigXML.RootElement()->IterateChildren("node", lpMapNode);
if (lpMapNode) 
{
    rms::CStationMapping litem;
    const TiXmlNode* lpItemNode = NULL ;
    while(lpItemNode = lpMapNode->IterateChildren("item",lpItemNode))
    {
        string str = lpItemNode->ToElement()->Attribute("ABC"); 
    }
}

遍历元素属性


TiXmlAttribute* pAttr = NULL; 
for (pAttr = pNode->FirstAttribute(); pAttr; pAttr = pAttr->Next())  
{    
  …
}

节点的下一个兄弟节点


const TiXmlNode* NextSibling() const;

元素的下一个元素


const TiXmlElement* NextSiblingElement() const;

属性的下一个属性


const TiXmlAttribute* Next() const;

返回值为NULL表示不存在

5.一个完整例子


void AppSettings::load(const char* pFilename)
{
    TiXmlDocument doc(pFilename);
    if (!doc.LoadFile()) return;

    TiXmlHandle hDoc(&doc);
    TiXmlElement* pElem;
    TiXmlHandle hRoot(0);

    // block: name
    {
        pElem=hDoc.FirstChildElement().Element();
        // should always have a valid root but handle gracefully if it does
        if (!pElem) return;
        m_name=pElem->Value();

        // save this for later
        hRoot=TiXmlHandle(pElem);
    }

    // block: string table
    {
        m_messages.clear(); // trash existing table

        pElem=hRoot.FirstChild( "Messages" ).FirstChild().Element();
        for( pElem; pElem; pElem=pElem->NextSiblingElement())
        {
            const char *pKey=pElem->Value();
            const char *pText=pElem->GetText();
            if (pKey && pText) 
            {
                m_messages[pKey]=pText;
            }
        }
    }

    // block: windows
    {
        m_windows.clear(); // trash existing list

        TiXmlElement* pWindowNode=hRoot.FirstChild( "Windows" ).FirstChild().Element();
        for( pWindowNode; pWindowNode; pWindowNode=pWindowNode->NextSiblingElement())
        {
            WindowSettings w;
            const char *pName=pWindowNode->Attribute("name");
            if (pName) w.name=pName;
            
            pWindowNode->QueryIntAttribute("x", &w.x); // If this fails, original value is left as-is
            pWindowNode->QueryIntAttribute("y", &w.y);
            pWindowNode->QueryIntAttribute("w", &w.w);
            pWindowNode->QueryIntAttribute("hh", &w.h);

            m_windows.push_back(w);
        }
    }

    // block: connection
    {
        pElem=hRoot.FirstChild("Connection").Element();
        if (pElem)
        {
            m_connection.ip=pElem->Attribute("ip");
            pElem->QueryDoubleAttribute("timeout",&m_connection.timeout);
        }
    }
}

到此这篇关于c++使用TinyXML解析XML的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程网。

--结束END--

本文标题: C++使用TinyXML解析XML

本文链接: https://www.lsjlt.com/news/160300.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • c语言怎么计算字符串长度
    在C语言中,可以使用内置的strlen()函数来计算字符串的长度。该函数位于string.h头文件中。以下是一个示例代码: #inc...
    99+
    2024-05-14
    c语言
  • c语言怎么判断三个数的大小
    可以通过比较三个数之间的大小关系来判断它们的大小。以下是一个示例代码: #include <stdio.h> int ...
    99+
    2024-05-14
    c语言
  • c++排序函数sort怎么使用
    在C++中,使用sort函数对容器中的元素进行排序,可以按照默认的升序排列,也可以自定义排序规则。 下面是一个简单的例子,对一个ve...
    99+
    2024-05-14
    c++
  • c++中string的compare函数怎么使用
    在C++中,可以使用string的compare函数来比较两个string对象的大小。该函数的原型如下: int compare(c...
    99+
    2024-05-14
    c++
  • c++中string的compare函数有什么用
    c++中string的compare函数用于比较两个字符串的大小关系。该函数返回一个整数值,表示两个字符串的比较结果。 具体来说,如...
    99+
    2024-05-14
    c++
  • c++中print函数的功能有哪些
    在C++中,通常使用std::cout来进行输出操作,而不是使用print函数。std::cout是C++标准库中的一个输出流对象,...
    99+
    2024-05-14
    c++
  • c语言数据结构怎么使用
    在C语言中,数据结构可以通过定义结构体来实现。以下是一些常见的数据结构的使用方法示例: 链表: #include <std...
    99+
    2024-05-14
    c语言
  • c++中print函数的用法是什么
    在C++中没有内置的print函数,但可以使用cout来输出内容到控制台。cout是C++标准库中的一个输出流对象,可以使用<...
    99+
    2024-05-14
    c++
  • c++中concept的用法是什么
    在C++20中,Concept是一种新的语言特性,用于定义类型要求和约束。Concept可以被用来约束函数模板、类模板和普通函数的参...
    99+
    2024-05-14
    c++
  • c++中concept的作用是什么
    在C++中,concept的作用是定义一种通用的约束,用于限制模板参数的类型范围。通过使用concept,可以在编译时对模板参数进行...
    99+
    2024-05-14
    c++
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作