当前位置:   article > 正文

xercesc库中文保存XML功能实现

xercesc库中文保存XML功能实现

目录

一 参考链接

二  运行结果

三 代码


一 参考链接

DOM Programming Guide (apache.org)

Xerces-c DOM XML文件的构造_xerces-c domimplementation-CSDN博客

Xerces-c库的使用-CSDN博客

二  运行结果

三 代码

  1. #include "XercesC_Test.h"
  2. #if 1
  3. //参考链接: https://blog.csdn.net/RGBMarco/article/details/81300814
  4. #include <xercesc/util/PlatformUtils.hpp>
  5. #include <xercesc/dom/DOM.hpp>
  6. #include <xercesc/framework/LocalFileFormatTarget.hpp>
  7. #include <xercesc/dom/DOMImplementationRegistry.hpp>
  8. #include <xercesc/dom/DOMImplementationLS.hpp>
  9. #include <xercesc/dom/DOMLSSerializer.hpp>
  10. #include <xercesc/util/PlatformUtils.hpp>
  11. #include <xercesc/util/XMLString.hpp>
  12. #include <xercesc/dom/DOMLSSerializerFilter.hpp>
  13. #include <xercesc/dom/DOMError.hpp>
  14. #include <xercesc/dom/DOMErrorHandler.hpp>
  15. #include <xercesc/framework/XMLFormatter.hpp>
  16. #include <xercesc/util/PlatformUtils.hpp>
  17. #include <xercesc/util/XMLString.hpp>
  18. #include <fstream>
  19. #include <iostream>
  20. #define Transcode_1(x) XMLString::transcode(x)
  21. #define Transcode_3(x,y,z) XMLString::transcode(x,y,z)
  22. using namespace xercesc;
  23. class MyDOMLSSerializerFilter : public xercesc::DOMLSSerializerFilter {
  24. public:
  25. // Constructor
  26. MyDOMLSSerializerFilter() {}
  27. // Destructor
  28. virtual ~MyDOMLSSerializerFilter() {}
  29. // 实现所有纯虚函数
  30. /**
  31. * Tells the DOMLSSerializer what types of nodes to show to the filter.
  32. * See <code>DOMNodeFilter</code> for definition of the constants.
  33. * The constant SHOW_ATTRIBUTE is meaningless here, attribute nodes will
  34. * never be passed to a DOMLSSerializerFilter.
  35. *
  36. * @return The constants of what types of nodes to show.
  37. * @since DOM Level 3
  38. */
  39. ShowType getWhatToShow() const {
  40. return 0;
  41. };
  42. // -----------------------------------------------------------------------
  43. // Virtual DOMLSSerializerFilter interface
  44. // -----------------------------------------------------------------------
  45. /** @name Functions introduced in DOM Level 3 */
  46. //@{
  47. /**
  48. * Interface from <code>DOMNodeFilter</code>,
  49. * to be implemented by implementation (derived class)
  50. */
  51. FilterAction acceptNode(const DOMNode* node) const {
  52. std::cout << "acceptNode: " << std::endl;
  53. return FilterAction::FILTER_ACCEPT;
  54. };
  55. };
  56. class MyDOMErrorHandler : public xercesc::DOMErrorHandler {
  57. public:
  58. // Constructor
  59. MyDOMErrorHandler() {}
  60. // Destructor
  61. virtual ~MyDOMErrorHandler() {}
  62. // Handles a warning received from the parser
  63. bool handleWarning(const xercesc::DOMError& domError) {
  64. // Here you can implement your own logic to handle warnings
  65. // For now, we just print the message and return true
  66. std::cout << "Warning: " << xercesc::XMLString::transcode(domError.getMessage()) << std::endl;
  67. return true;
  68. }
  69. // Handles an error received from the parser
  70. bool handleError(const xercesc::DOMError& domError) {
  71. // Here you can implement your own logic to handle errors
  72. // For now, we just print the message and return false
  73. std::cout << "Error: " << xercesc::XMLString::transcode(domError.getMessage()) << std::endl;
  74. return false;
  75. }
  76. // Handles a fatal error received from the parser
  77. bool handleFatalError(const xercesc::DOMError& domError) {
  78. // Here you can implement your own logic to handle fatal errors
  79. // For now, we just print the message and return false
  80. std::cout << "Fatal Error: " << xercesc::XMLString::transcode(domError.getMessage()) << std::endl;
  81. return false;
  82. }
  83. // Resets the error handler
  84. void resetErrors() {
  85. // Here you can implement your own logic to reset errors if needed
  86. }
  87. };
  88. class StdOutFormatTarget : public xercesc::XMLFormatTarget {
  89. public:
  90. // -----------------------------------------------------------------------
  91. // Virtual interface
  92. // -----------------------------------------------------------------------
  93. void writeChars(
  94. const XMLByte* const toWrite
  95. , const XMLSize_t count
  96. , XMLFormatter* const formatter) {};
  97. void flush() {};
  98. };
  99. int main()
  100. {
  101. try
  102. {
  103. //XMLPlatformUtils::Initialize();//en_US
  104. XMLPlatformUtils::Initialize("zh_CN");
  105. }
  106. catch (const XMLException& toCatch)
  107. {
  108. std::cerr << Transcode_1(toCatch.getMessage());
  109. }
  110. try
  111. {
  112. //DOMImplementation* imp = DOMImplementationRegistry::getDOMImplementation(Transcode_1("Core"));
  113. DOMImplementation* imp = DOMImplementationRegistry::getDOMImplementation(L"LS");
  114. DOMLSOutput* output = dynamic_cast<DOMImplementationLS*>(imp)->createLSOutput();
  115. DOMLSSerializer* serial = dynamic_cast<DOMImplementationLS*>(imp)->createLSSerializer();
  116. output->setEncoding(L"UTF-8");
  117. DOMLSSerializerFilter* filter = new MyDOMLSSerializerFilter();
  118. serial->setFilter(filter);
  119. // optionally you can implement your DOMErrorHandler (e.g. MyDOMErrorHandler)
  120. // and set it to the serializer
  121. DOMErrorHandler* errHandler = new MyDOMErrorHandler();
  122. serial->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, errHandler);
  123. // StdOutFormatTarget prints the resultant XML stream
  124. // to stdout once it receives any thing from the serializer.
  125. XMLFormatTarget* myFormTarget = new StdOutFormatTarget();
  126. const wchar_t* str = L"a中文.xml";
  127. XMLFormatTarget* target = new LocalFileFormatTarget(str);
  128. output->setByteStream(target);
  129. // set user specified end of line sequence and output encoding
  130. serial->setNewLine(L"\r");
  131. // set serializer features
  132. serial->getDomConfig()->setParameter(XERCES_CPP_NAMESPACE_QUALIFIER XMLUni::fgDOMWRTSplitCdataSections, false);
  133. serial->getDomConfig()->setParameter(XERCES_CPP_NAMESPACE_QUALIFIER XMLUni::fgDOMWRTSplitCdataSections, false);
  134. serial->getDomConfig()->setParameter(XERCES_CPP_NAMESPACE_QUALIFIER XMLUni::fgDOMWRTDiscardDefaultContent, false);
  135. serial->getDomConfig()->setParameter(XERCES_CPP_NAMESPACE_QUALIFIER XMLUni::fgDOMWRTFormatPrettyPrint, true);//换行
  136. serial->getDomConfig()->setParameter(XERCES_CPP_NAMESPACE_QUALIFIER XMLUni::fgDOMWRTBOM, false);
  137. DOMDocument* doc = imp->createDocument(0, Transcode_1("root"), 0);
  138. const wchar_t* strNode1 = L"node1中文";
  139. DOMElement* node = doc->createElement(L"node1");
  140. node->setAttribute(Transcode_1("name"), L"node1");
  141. node->setTextContent(strNode1);
  142. DOMElement* root = doc->getDocumentElement();
  143. root->appendChild(node);
  144. DOMElement* node2 = doc->createElement(Transcode_1("node2"));
  145. node2->setAttribute(Transcode_1("name"), Transcode_1("node2"));
  146. node2->setTextContent(Transcode_1("node2"));
  147. root->appendChild(node2);
  148. DOMElement* node2_1 = doc->createElement(Transcode_1("node2_1"));
  149. node2_1->setAttribute(Transcode_1("name"), Transcode_1("node2_1"));
  150. node2_1->setTextContent(Transcode_1("node2_1"));
  151. node2->appendChild(node2_1);
  152. DOMElement* node2_2 = doc->createElement(Transcode_1("node2_2"));
  153. node2_2->setAttribute(Transcode_1("name"), Transcode_1("node2_2"));
  154. node2_2->setTextContent(Transcode_1("node2_2"));
  155. node2->appendChild(node2_2);
  156. if (doc)
  157. {
  158. doc->setXmlStandalone(true);
  159. serial->write(doc, output);
  160. doc->release();
  161. serial->release();
  162. delete target;
  163. }
  164. }
  165. catch (const DOMException& toCatch)
  166. {
  167. std::cerr << Transcode_1(toCatch.getMessage());
  168. }
  169. return 0;
  170. }
  171. #endif
  172. #if 0
  173. //https://blog.csdn.net/RGBMarco/article/details/81253563
  174. #include <iostream>
  175. #include <xercesc/dom/DOM.hpp>
  176. #include <xercesc/util/PlatformUtils.hpp>
  177. #include <xercesc/parsers/XercesDOMParser.hpp>
  178. #include <xercesc/sax/SAXException.hpp>
  179. #include <xercesc/sax/HandlerBase.hpp>
  180. #include <string>
  181. #include <vector>
  182. using namespace std;
  183. using namespace xercesc;
  184. #define STUDENTS_TAG "Students"
  185. #define STUDENT_TAG "Student"
  186. #define NAME_TAG "Name"
  187. #define AGE_TAG "Age"
  188. #define SEX_TAG "Sex"
  189. struct Student {
  190. string Name;
  191. int Age;
  192. string Sex;
  193. };
  194. enum ErrorCode
  195. {
  196. LACK_BEGIN = 1, // 缺少<Students>标记
  197. LACK_NAME = 2, // 缺少姓名
  198. LACK_AGE = 3, // 缺少年龄
  199. LACK_SEX = 4 // 缺少性别
  200. };
  201. DOMElement* findStudentsTag(DOMElement* root)
  202. {
  203. if (root == 0)
  204. return 0;
  205. if (XMLString::compareString(XMLString::transcode(root->getTagName()), STUDENTS_TAG) == 0)
  206. return root;
  207. else
  208. return findStudentsTag(root->getNextElementSibling());
  209. }
  210. int visitDom2GetStudents(DOMElement* root, vector<Student>& students)
  211. {
  212. DOMElement* stustag = findStudentsTag(root);
  213. if (stustag == 0)
  214. return LACK_BEGIN;
  215. DOMNodeList* stulist = root->getElementsByTagName(XMLString::transcode(STUDENT_TAG));
  216. size_t length = stulist->getLength();
  217. for (size_t index = 0; index < length; ++index)
  218. {
  219. DOMElement* elems = dynamic_cast<DOMElement*>(stulist->item(index));
  220. DOMElement* name = elems->getFirstElementChild();
  221. Student stu;
  222. if (name == 0)
  223. return LACK_NAME;
  224. if (XMLString::compareString(XMLString::transcode(name->getTagName()), NAME_TAG) == 0)
  225. {
  226. DOMNode* n = dynamic_cast<DOMNode*>(name);
  227. stu.Name = static_cast<string>(XMLString::transcode(n->getTextContent()));
  228. }
  229. else
  230. return LACK_NAME;
  231. DOMElement* age = name->getNextElementSibling();
  232. if (age == 0)
  233. return LACK_AGE;
  234. if (XMLString::compareString(XMLString::transcode(age->getTagName()), AGE_TAG) == 0)
  235. {
  236. DOMNode* n = dynamic_cast<DOMNode*>(age);
  237. stu.Age = atoi(XMLString::transcode(n->getTextContent()));
  238. }
  239. else
  240. return LACK_AGE;
  241. DOMElement* sex = age->getNextElementSibling();
  242. if (sex == 0)
  243. {
  244. return LACK_SEX;
  245. }
  246. if (XMLString::compareString(XMLString::transcode(sex->getTagName()), SEX_TAG) == 0)
  247. {
  248. DOMNode* n = dynamic_cast<DOMNode*>(sex);
  249. stu.Sex = static_cast<string>(XMLString::transcode(n->getTextContent()));
  250. }
  251. else
  252. return LACK_SEX;
  253. students.emplace_back(stu);
  254. }
  255. return 0;
  256. }
  257. int main()
  258. {
  259. try
  260. {
  261. XMLPlatformUtils::Initialize();
  262. }
  263. catch (const XMLException& toCatch)
  264. {
  265. std::cerr << XMLString::transcode(toCatch.getMessage());
  266. return -1;
  267. }
  268. XercesDOMParser* parser = new XercesDOMParser();
  269. ErrorHandler* errHandler = new HandlerBase();
  270. parser->setErrorHandler(errHandler);
  271. try
  272. {
  273. parser->parse("test.xml");
  274. }
  275. catch (const XMLException& toCatch)
  276. {
  277. std::cerr << XMLString::transcode(toCatch.getMessage());
  278. return -1;
  279. }
  280. catch (const DOMException& toCatch)
  281. {
  282. std::cerr << XMLString::transcode(toCatch.getMessage());
  283. return -1;
  284. }
  285. catch (const SAXException& toCatch)
  286. {
  287. std::cerr << XMLString::transcode(toCatch.getMessage());
  288. return -1;
  289. }
  290. DOMDocument* doc = parser->getDocument();
  291. DOMElement* root = doc->getDocumentElement();
  292. vector<Student> students;
  293. int ret = visitDom2GetStudents(root, students);
  294. if (ret != 0)
  295. std::cerr << "Parse error\n";
  296. else
  297. {
  298. for (auto stu : students)
  299. {
  300. std::cout << "Name: " << stu.Name << "\n"
  301. << " Age: " << stu.Age << "\n"
  302. << " Sex: " << stu.Sex << "\n";
  303. }
  304. }
  305. doc->release();
  306. XMLPlatformUtils::Terminate();
  307. return 0;
  308. }
  309. #endif

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/280565
推荐阅读