XMLWriter - 一个简单的可重用类






4.86/5 (39投票s)
可重用代码示例 - XML 编写器类
引言
XMLwriter
是一个简单的类,可以在您的应用程序中使用它来创建/生成 XML 输出。 您需要做的就是将 xmlwriter.h 和 xmlwriter.cpp 包含到您的项目中,然后享受它。
该实现仅使用标准的 CPP 库和 STL,因此可以在 Windows 以及 Linux 应用程序中使用。 我已经在 Windows 环境、Cygwin(Linux 模拟器)和 Linux 系统中使用过它。 在这三个环境中它都能正常工作。 希望在其他操作系统中也能得到相同的结果。
这个 XMLWriter
类并不支持 XML 的所有功能,但肯定能满足您在大多数应用程序中的基本需求。 您可以免费使用此代码,但请自行承担风险。(请测试应用程序。)
特点
- 轻松创建节点
- 轻松创建元素
- 轻松添加属性
- 使用一个简单的命令关闭所有打开的标签(使用堆栈来跟踪所有打开的标签)
- 无需担心文件操作(所有操作均在内部处理)
缺失的功能
- 未对文件进行验证和确认(用户有责任确保文件格式正确且有效)
- 目前,缺少添加处理指令和 CDATA 部分的配置。 如果您需要,可以轻松地将其添加到 XML 类中。
我将教程组织成三个主要部分
- 第一部分:如何使用?
- 第二部分:示例实现
- 第三部分:设计概述(以便您可以添加、删除和修改现有功能)
第一部分:如何使用?
使用非常简单易懂。
Windows 用户
- 在您使用的 IDE 中创建一个简单的项目。
- 添加文件 xmlwriter.cpp 和 xmlwriter.h。
- 创建一个主应用程序。
- 创建一个 ‘
xmlwriter
’ 对象,并使用成员函数添加节点、元素等。
Linux 用户
将文件 xmlwriter.cpp 和 xmlwriter.h 复制到您的工作目录中。 创建一个主应用程序,例如 testxmlwriter.cpp。 创建一个 make 文件。
#make file created by boby
#March-2006
CC = g++ -Wno-deprecated
CFLAGS = -c
XMLwriter_cygwin : xmlwriter.o testxmlwriter.o
$(CC) xmlwriter.o testxmlwriter.o -o XMLwriter_cygwin
xmlwriter.o : xmlwriter.cpp
$(CC) $(CFLAGS) xmlwriter.cpp
testxmlwriter.o : testxmlwriter.cpp
$(CC) $(CFLAGS) testxmlwriter.cpp
clean:
-rm -f *.o
第二部分:示例实现
xmlwriter MyXml("boby.xml");
//creates an object of type xmlwriter'. This object
//is closely coupled to the xml file boby.xml.
//Whatever operation you perform on this object
//will be reflected in the boby.xml file.
//Constructor adds the following lines to the xml files.
//Change the constructor code if you want to
//change the encoding format.
<?xml version="1.0" encoding="UTF-8" ?>
MyXml.AddAtributes("age","25");
//add an attribute "age" with value "25" into memory.
//This attribute will be added to the next tag which will be created.
//You can add any number of attributes before adding the tag.
//All the attributes will be added to the next tag created.
MyXml.AddAtributes("Profession","Software");
// add one more attribute.
MyXml.Createtag("Boby");
// this will create a tag boby with two attributes
// "age" and "Profession".
MyXml.AddComment("Personal information");
MyXml.Createtag("Home"); // create node boby
MyXml.CreateChild("Address","Pazheparampil"); // add element
MyXml.CreateChild("Mobile","09844400873");
MyXml.CloseLasttag(); // close boby
MyXml.AddComment("Office information");
MyXml.Createtag("Office"); // create node boby
MyXml.CreateChild("Address","Bangalore"); // add element
MyXml.CreateChild("Ph","0091234567");
MyXml.CloseLasttag(); // close Office
MyXml.CloseAlltags();
//This will close all the open tags. After going deep
//into the file creating lots of XML nodes,
//you can close the all opened tags with this single function call.
//A stack has been implemented to keep track of all the open tags.
第三部分:设计概述
类图
摘要
这个 XML writer 类是一个可重用类的典型示例。 由于该类仅处理 XML 操作,因此可以在任何应用程序中轻松重用,而无需修改任何代码。