`

Xerces-C++学习之——查询修改XML文档 (转)

 
阅读更多

/*
* ===========================================================================
*
* Filename: ParseXML.cpp
*
* Description: This is an example of the use of Xerces-C++ operation XML.
*
* Version: 1.0
* Created: 03/01/2010 09:44:19 AM
* Revision: none
* Compiler: gcc
*
* Author: huabo (caodaijun), caodaijun@feinno.com
* Company: feinno
*
* ===========================================================================
*/
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
#include <xercesc/framework/MemBufFormatTarget.hpp>
#include <xercesc/framework/StdOutFormatTarget.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>

#include <string>

#if defined(XERCES_NEW_IOSTREAMS)
#include <iostream>
#else
#include <iostream.h>
#endif

XERCES_CPP_NAMESPACE_USE
class XStr
{
public:
XStr(const char* const toTranscode)
{
fUnicodeForm = XMLString::transcode(toTranscode);
}
~XStr()
{
XMLString::release(&fUnicodeForm);
}
const XMLCh* unicodeForm() const
{
return fUnicodeForm;
}
private:
XMLCh* fUnicodeForm;
};

#define X(str) XStr(str).unicodeForm()

std::string xml_string =
"<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><corporation xmlns='com:cmcc:corporation' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='com:cmcc:corporation corporation.xsd'><eid>100000</eid><basic><corp_name>abcd</corp_name><corp_code/><c0/><short_name/><calling_code/><legal_representative/><address/><zip/><telephone/><fax/><contact/><proportion_code/><logo_crc/><employee_portrait_crc/><group_portrait_crc/><createtime/><opentime/><province_code/><vgop_code/><org_version/><source_code/><client_dept_version/><version_id/><contact_mp/></basic><rules><order_flag/><demo_flag/><useroperate_limit/><emp_portrait_flag/><iplmt/><dept_auth_switch/><sms_block/><sms_begin/><sms_end/><edit_status/><expire_time/></rules><accounts><scale_code/><customer_manager/><manager_phone/><deposit_bank/><bank_accounts/><password_paper_id/><group_code/><sms_code/><meeting_code/><fee_code/><cycle_code/><sharedisk_code/><sp_status/><updatetime/></accounts></corporation>";

std::string basic_string = "<basic><test>good</test></basic>";

int main(int argC, char*argV[])
{
// Initialize the XML4C2 system.
try
{
XMLPlatformUtils::Initialize();
}
catch(const XMLException& toCatch)
{
char *pMsg = XMLString::transcode(toCatch.getMessage());
XERCES_STD_QUALIFIER cerr << "Error during Xerces-c Initialization.\n"
<< " Exception message:"
<< pMsg;
XMLString::release(&pMsg);
return 1;
}

DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(X("LS"));
DOMLSSerializer* theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer();
DOMLSOutput *theOutputDesc = ((DOMImplementationLS*)impl)->createLSOutput();
MemBufFormatTarget* target = new MemBufFormatTarget();
theOutputDesc->setByteStream(target);

if (impl != NULL)
{
try
{

XercesDOMParser* parser = new XercesDOMParser();

MemBufInputSource* xml_mem = new MemBufInputSource(
(const XMLByte* )xml_string.c_str(),
xml_string.length(),
"xml",
false);
parser->parse( *xml_mem );
DOMDocument* xml_doc = parser->getDocument();
DOMElement* xml_root = xml_doc->getDocumentElement();
if (NULL == xml_root)
{
std::cout<< "Empty XML document!\n";
exit(1);
}
//输出整个文档
std::cout<< XMLString::transcode(theSerializer->writeToString((DOMNode* )xml_root))<< std::endl;

//输出XPATH指定的结点
DOMXPathNSResolver* resolver = xml_doc->createNSResolver(xml_root);
DOMXPathResult* result = xml_doc->evaluate(
X("/corporation/basic"),
xml_root,
resolver,
DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE,
NULL);
result->snapshotItem(0);
DOMNode* curentNode = result->getNodeValue();
DOMNode* prevNode = curentNode->getParentNode();
theSerializer->write(curentNode, theOutputDesc);
std::cout<< target->getRawBuffer()<< std::endl;

//replace the basic child
MemBufInputSource* basic_mem = new MemBufInputSource(
(const XMLByte* )basic_string.c_str(),
basic_string.length(),
"basic",
false);
parser->parse( *basic_mem );
DOMDocument* basic_doc = parser->getDocument();
DOMElement* basic_root = basic_doc->getDocumentElement();
DOMNode* newnode = xml_doc->importNode((DOMNode* )basic_root, true);
prevNode->replaceChild(newnode, curentNode);

//再次输出整个文档
std::cout<< XMLString::transcode(theSerializer->writeToString((DOMNode* )xml_root))<< std::endl;

delete basic_mem;
delete xml_mem;
delete target;
delete parser;
result->release();
resolver->release();
theOutputDesc->release();
theSerializer->release();
}
catch(const OutOfMemoryException&)
{
XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
}
catch (const DOMException& e)
{
XERCES_STD_QUALIFIER cerr << "DOMException code is: " << e.code << XERCES_STD_QUALIFIER endl;
}
catch (...)
{
XERCES_STD_QUALIFIER cerr << "An error occurred creating the document" << XERCES_STD_QUALIFIER endl;
}
}
else
{
XERCES_STD_QUALIFIER cerr << "Requested implementation is not supported" << XERCES_STD_QUALIFIER endl;
}

XMLPlatformUtils::Terminate();
return 0;
}

 

转:http://blog.chinaunix.net/uid-17240700-id-2813918.html

分享到:
评论
1 楼 xiejanee 2014-08-15  
楼主:你好!我想请问下  你在代码中用DOMDocument* xml_doc = parser->getDocument();语句创建了doc 但是最后在清理内存的时候为什么没有将doc所指向的内存空间释放?
我在处理xml文件时遇到了一个问题 就是自己写的一个类中需要实现对xml文件的修改以及保存 所以代码中用到了xerces的dom方式对xml文件进行修改  代码中有paser以及doc的创建语句 :
XercesDOMParser *parser = new XercesDOMParser;
xercesc_3_1::DOMDocument *doc = parser->getDocument();
在xml文件处理完后,想同时释放类对象中parser 以及 doc所指向的内存空间,此时就会报内存读取错误, 我是用doc->release();delete parser;这两条语句对两者进行空间清理的,但是若只调用其中的一个语句对相应指针的指向空间进行清理时,就不会报错,难道parser所指向的内存空间和doc说指向的内存空间有重叠部分吗,以至于两条语句会清理同一块内存区域? 请楼主指教 谢谢。

相关推荐

    xerces-c-3.2.3.zip

    Xerces-C++是Apache软件基金会的一个重要项目,它是一款高效且可移植的XML文档解析器,支持多种编程语言,其中包括我们这里的焦点——C++。标题中的"xerces-c-3.2.3.zip"指示的是Xerces-C++的3.2.3版本,专为64位...

    Xerces-J-tools.2.11.0-xml-schema-1.1-beta.zip下载

    Xerces是由Apache组织所推动的一项XML文档解析开源项目,它目前有多种语言版本包括JAVA、C++、PERL、COM等。[1] Xerces是一个开放源代码的XML语法分析器。从JDK1.5以后,Xerces就成了JDK的XML默认实现 Xerces-C++ 的...

    xerces-c-src_2_8_0.tar.gz

    首先,我们来看Xerces-C++的核心功能——XML解析。Xerces-C++支持XML 1.0和1.1标准,能够解析XML文档并将其转换为内存中的数据结构。它的解析过程分为两个主要阶段:词法分析和语法分析。词法分析将XML文档分解为一...

    Xerces-J-src.1.3.1.zip

    《Xerces-J-src.1.3.1.zip——深入理解SAX XML解析器》 在信息化时代,XML(eXtensible Markup Language)作为数据交换和存储的标准格式,广泛应用于各种应用程序之间。XML文件的解析是处理XML文档的基础,其中SAX...

    c++ xml解析工具——tinyxml

    然而,对于大型、复杂的XML文档或者需要高性能解析的情况,可能需要考虑使用更强大的XML解析库,如pugixml、Xerces-C++或 RapidXML。但总体而言,TinyXML对于初学者和小型项目来说,是一个理想的XML解析工具。

    TinyXML——类库+doc

    1. **TiXMLDocument**:这是 TinyXML 的核心类,代表整个XML文档。你可以通过它加载XML文件,或者创建一个新的XML文档并添加元素。 2. **TiXmlElement**:这个类表示XML文档中的一个元素。元素是XML文档的基本构建...

    xml解析中文笔记.docx

    - **优点**:保持了XML文档中元素间的结构关系,便于数据查询和操作。 - **缺点**:对于大型文档来说可能导致内存溢出,效率较低。 - **SAX**(简单API for XML):是一种事件驱动的解析模式,它不要求将整个文档...

    linux下的飞鸽安装

    在Linux环境下安装飞鸽软件的过程中,我们需要注意一个关键的依赖性——XML解析器。XML(Extensible Markup Language)是一种用于标记数据的语言,广泛应用于配置文件、数据交换和文档存储等领域。飞鸽作为一款应用...

    XQilla-开源

    Xerces-C为XQilla提供了强大的XML解析功能,使得开发者能够高效地处理XML文档,进行复杂的查询和数据提取。 XQuery是一种强大的查询语言,专门用于从XML文档中检索数据。它允许用户以结构化的方式查询XML文档,提取...

Global site tag (gtag.js) - Google Analytics