在 Windows 上使用 Xerces 3.0.1 和 C++ 编写 XML

2024-03-23

我编写了以下函数来使用 Xerces 3.0.1 创建 XML 文件,如果我使用“foo.xml”或“../foo.xml”的文件路径调用此函数,它会很好用,但如果我传入“c:/foo.xml”然后我在这一行得到一个异常

XMLFormatTarget *formatTarget = new LocalFileFormatTarget(targetPath);

有人可以解释为什么我的代码适用于相对路径,但不适用于绝对路径吗? 非常感谢。

const int ABSOLUTE_PATH_FILENAME_PREFIX_SIZE = 9;

void OutputXML(xercesc::DOMDocument* pmyDOMDocument, std::string filePath)
{
    //Return the first registered implementation that has the desired features. In this case, we are after a DOM implementation that has the LS feature... or Load/Save.
    DOMImplementation *implementation = DOMImplementationRegistry::getDOMImplementation(L"LS");

    // Create a DOMLSSerializer which is used to serialize a DOM tree into an XML document.
    DOMLSSerializer *serializer = ((DOMImplementationLS*)implementation)->createLSSerializer();

    // Make the output more human readable by inserting line feeds.
    if (serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
        serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);

    // The end-of-line sequence of characters to be used in the XML being written out. 
    serializer->setNewLine(XMLString::transcode("\r\n")); 

    // Convert the path into Xerces compatible XMLCh*.
    XMLCh *tempFilePath = XMLString::transcode(filePath.c_str());

    // Calculate the length of the string.
    const int pathLen = XMLString::stringLen(tempFilePath);

    // Allocate memory for a Xerces string sufficent to hold the path.
    XMLCh *targetPath = (XMLCh*)XMLPlatformUtils::fgMemoryManager->allocate((pathLen + ABSOLUTE_PATH_FILENAME_PREFIX_SIZE) * sizeof(XMLCh));

    // Fixes a platform dependent absolute path filename to standard URI form.
    XMLString::fixURI(tempFilePath, targetPath);

    // Specify the target for the XML output.
    XMLFormatTarget *formatTarget = new LocalFileFormatTarget(targetPath);
    //XMLFormatTarget *myFormTarget = new StdOutFormatTarget();

    // Create a new empty output destination object.
    DOMLSOutput *output = ((DOMImplementationLS*)implementation)->createLSOutput();

    // Set the stream to our target.
    output->setByteStream(formatTarget);

    // Write the serialized output to the destination.
    serializer->write(pmyDOMDocument, output);

    // Cleanup.
    serializer->release();
    XMLString::release(&tempFilePath);
    delete formatTarget;
    output->release();
}

您的文件路径似乎不正确。它应该是 file:///C:/。请参阅以下内容了解更多信息:

http://en.wikipedia.org/wiki/File_URI_scheme http://en.wikipedia.org/wiki/File_URI_scheme

UPDATE:以下代码适用于 Visual Studio 2008。使用您的代码以及 Xerces 附带的一些示例,这是一个快速破解。

#include <windows.h>
#include <iostream>
#include <string>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
#include <xercesc/framework/XMLFormatter.hpp>
#include <xercesc/framework/LocalFileFormatTarget.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMImplementation.hpp>
#include <xercesc/dom/DOMImplementationRegistry.hpp>
#include <xercesc/dom/DOMLSSerializer.hpp>
#include <xercesc/dom/DOMLSOutput.hpp>


using namespace xercesc;
using namespace std;

void OutputXML(xercesc::DOMDocument* pmyDOMDocument, std::string filePath);

class XStr
{
public :
    XStr(const char* const toTranscode)
    {
        // Call the private transcoding method
        fUnicodeForm = XMLString::transcode(toTranscode);
    }

    ~XStr()
    {
        XMLString::release(&fUnicodeForm);
    }

    const XMLCh* unicodeForm() const
    {
        return fUnicodeForm;
    }

private :
    XMLCh*   fUnicodeForm;
};

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

int _tmain(int argc, _TCHAR* argv[])
{
    try
    {
        XMLPlatformUtils::Initialize();
    }
    catch(const XMLException& e)
    {
        char* message = XMLString::transcode(e.getMessage());
        cout << "Error Message: " << message << "\n";
        XMLString::release(&message);
        return 1;
    }

    int errorCode = 0;
    {

        DOMImplementation* impl =  DOMImplementationRegistry::getDOMImplementation(X("Core"));

        if (impl != NULL)
        {
            try
            {
                DOMDocument* doc = impl->createDocument(
                               0,                    // root element namespace URI.
                               X("company"),         // root element name
                               0);                   // document type object (DTD).

                DOMElement* rootElem = doc->getDocumentElement();

                DOMElement*  prodElem = doc->createElement(X("product"));
                rootElem->appendChild(prodElem);

                DOMText*    prodDataVal = doc->createTextNode(X("Xerces-C"));
                prodElem->appendChild(prodDataVal);

                DOMElement*  catElem = doc->createElement(X("category"));
                rootElem->appendChild(catElem);

                catElem->setAttribute(X("idea"), X("great"));

                DOMText*    catDataVal = doc->createTextNode(X("XML Parsing Tools"));
                catElem->appendChild(catDataVal);

                DOMElement*  devByElem = doc->createElement(X("developedBy"));
                rootElem->appendChild(devByElem);

                DOMText*    devByDataVal = doc->createTextNode(X("Apache Software Foundation"));
                devByElem->appendChild(devByDataVal);

                OutputXML(doc, "C:/Foo.xml");

                doc->release();
            }
            catch (const OutOfMemoryException&)
            {
                XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
                errorCode = 5;
            }
            catch (const DOMException& e)
            {
                XERCES_STD_QUALIFIER cerr << "DOMException code is:  " << e.code << XERCES_STD_QUALIFIER endl;
                errorCode = 2;
            }
            catch(const XMLException& e)
            {
                char* message = XMLString::transcode(e.getMessage());
                cout << "Error Message: " << message << endl;
                XMLString::release(&message);
                return 1;
            }
            catch (...)
            {
                XERCES_STD_QUALIFIER cerr << "An error occurred creating the document" << XERCES_STD_QUALIFIER endl;
                errorCode = 3;
            }
       }  // (inpl != NULL)
       else
       {
           XERCES_STD_QUALIFIER cerr << "Requested implementation is not supported" << XERCES_STD_QUALIFIER endl;
           errorCode = 4;
       }
    }

    XMLPlatformUtils::Terminate();

    return errorCode;
}

void OutputXML(xercesc::DOMDocument* pmyDOMDocument, std::string filePath) 
{ 
    //Return the first registered implementation that has the desired features. In this case, we are after a DOM implementation that has the LS feature... or Load/Save. 
    DOMImplementation *implementation = DOMImplementationRegistry::getDOMImplementation(L"LS"); 

    // Create a DOMLSSerializer which is used to serialize a DOM tree into an XML document. 
    DOMLSSerializer *serializer = ((DOMImplementationLS*)implementation)->createLSSerializer(); 

    // Make the output more human readable by inserting line feeds. 
    if (serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true)) 
        serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true); 

    // The end-of-line sequence of characters to be used in the XML being written out.  
    serializer->setNewLine(XMLString::transcode("\r\n"));  

    // Convert the path into Xerces compatible XMLCh*. 
    XMLCh *tempFilePath = XMLString::transcode(filePath.c_str()); 

    // Specify the target for the XML output. 
    XMLFormatTarget *formatTarget = new LocalFileFormatTarget(tempFilePath); 

    // Create a new empty output destination object. 
    DOMLSOutput *output = ((DOMImplementationLS*)implementation)->createLSOutput(); 

    // Set the stream to our target. 
    output->setByteStream(formatTarget); 

    // Write the serialized output to the destination. 
    serializer->write(pmyDOMDocument, output); 

    // Cleanup. 
    serializer->release(); 
    XMLString::release(&tempFilePath); 
    delete formatTarget; 
    output->release(); 
} 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Windows 上使用 Xerces 3.0.1 和 C++ 编写 XML 的相关文章

  • 中间件 API 的最佳实践是什么? [关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我们正在开发一个中间件 SDK 采用 C 和 Java 语言 供游戏开发人员 动画软件开发人员 阿凡达开
  • 同步执行异步函数

    我对此主题进行了大量搜索 并且阅读了本网站上有关此主题的大部分帖子 但是我仍然感到困惑 我需要一个直接的答案 这是我的情况 我有一个已建立的 Winform 应用程序 但无法使其全部 异步 我现在被迫使用一个全部编写为异步函数的外部库 在我
  • C++ 模板中的名称查找

    我有一些 C 代码 如果没有 fpermissive 选项 就无法再编译 这是我无法分享的专有代码 但我认为我已经能够提取一个简单的测试用例来演示该问题 这是 g 的输出 template eg cpp In instantiation o
  • gtest 和 gmock 有什么区别?

    我试图理解的目的google mock Google 的 C 模拟框架 https github com google googletest blob master googlemock README md 我已经与gtest较早 但我还是
  • 将指针转换为浮点数?

    我有一个unsigned char 通常 这指向一块数据 但在某些情况下 指针就是数据 即 铸造一个int的价值unsigned char 指针 unsigned char intData unsigned char myInteger 反
  • 隐式方法组转换陷阱

    我想知道为什么给定代码的输出 在 LinqPad 中执行 void Main Compare1 Action Main Dump Compare2 Main Dump bool Compare1 Delegate x return x Ac
  • 泛型与接口的实际优势

    在这种情况下 使用泛型与接口的实际优势是什么 void MyMethod IFoo f void MyMethod
  • 我们如何将数据从一个打开的表单传递到另一个打开的表单?

    winform中如何将数据从一个窗体传递到另一个打开的窗体 在 Windows 应用程序中 一个窗体打开另一个窗体 当我在父表单中输入一些数据时 这些数据将立即反映在另一个子表单中 这将如何发生 取决于你想要多花哨 最简单的方法就是直接调用
  • 使用静态类型代替变量

    当您的项目不使用命名空间时 有什么方法可以告诉编译器使用静态类型而不是变量吗 例如 我有一个名为 User 的类 它具有各种静态和非静态方法 假设调用了其中一个静态方法GetUser 我想称之为User GetUser 方法来自一个方法 该
  • 如何从 List 中的字符串中删除数字/数字?

    我有一个字符串列表 List
  • 使用 Selenium for C# 登录 Facebook

    我一直在使用 Selenium C 框架并尝试进行 facebook 登录 但没有任何运气 这是我到目前为止得到的 基于这篇文章 使用 Selenium 测试 Facebook Connect 应用程序 https stackoverflo
  • Entity Framework 4.1 RC:Code First EntityTypeConfiguration 继承问题

    我尝试使用通用的 EntityTypeConfiguration 类来配置所有实体的主键 以便每个派生的配置类不会重复自身 我的所有实体都实现一个公共接口 IEntity 它表示每个实体必须有一个 int 类型的 Id 属性 我的配置基类如
  • C++ 私有静态成员变量

    此 C 代码在编译时产生链接器错误 A h class A public static void f private static std vector
  • 膨胀类片段 InflateException 二进制 XML 文件时出错

    我正在使用 Material Design 和 NavigationDrawer 布局等设计我的第一个应用程序 但我遇到了一个问题 该应用程序非常简单 它只显示文本 并且基于 Android Studio 中提供的模板 尝试启动我的应用程序
  • 简单的文档管理系统和API [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • Active Directory UserPrincipal.Current.GetGroups() 返回本地组而不是 Web 服务器上的组

    以下内容在我的本地开发盒上效果很好 但是 当我将其移动到网络服务器时 它失败了 甚至不会记录错误 public static List
  • System.diagnostics.process 进程在托管后无法在 IIS 上运行?

    我正在尝试从网络应用程序安装 exe 当我在本地运行应用程序 从 asp 开发服务器 时 它安装正确 但当我托管在 IIS 上时 它不起作用 我在asp net页面的Page load方法上编写了这段代码 想要在客户端计算机上安装Test
  • 带属性的 XML 模式限制

    在XML Schema中 如何创建元素Age具有restriction允许在元素内部写入最大值为 10 最小值为 1 的整数Age还有元素Age有属性
  • C 中的 N 依赖注入 - 比链接器定义的数组更好的方法?

    Given a 库模块 在下文中称为Runner 它作为可重复使用的组件 无需重新编译 即静态链接库 中应用程序分区架构的 而不是主分区 请注意 它仅包含main 出于演示目的 Given a set 顺序无关 调用的其他模块 对象Call
  • 编译器可以报告未知属性的错误吗?即使有范围?

    在N3291 7 6 1 3 5 属性语法和语义 decl attr grammar 关于如何属性是用我读过的源代码写的 使用一个属性范围令牌是有条件支持的 实现定义的行为 and For an 属性标记本国际标准中未指定 该行为是实现定义

随机推荐

  • wpf mvvm ..访问视图模型中的视图元素

    我正处于学习 wpf mvvm 的阶段 因为我知道在 vm 中我们声明命令并将它们绑定到视图元素的事件 而不是在代码隐藏文件中执行此操作 我没有得到的是 我们将如何访问视图元素和事件参数 您的 ViewModel 不会直接访问视图中的元素
  • Luis 的 Azure 密钥不可用

    我正在尝试发布我的 LUIS 应用程序的暂存版本 我已在 Azure 澳大利亚东部设置了认知服务应用程序 并且可以在 Azure 门户中看到密钥 然而在 AU Luis 门户网站中https au luis ai https au luis
  • 使用相同的 udp 套接字进行异步接收/发送

    我在 udp 服务器中使用相同的套接字 以便在某个端口上接收来自客户端的数据 然后在处理请求后使用 ip ud socket async send to 响应客户端 接收也是与 async receive from 异步完成的 套接字使用相
  • Knuth 计算机编程艺术 ex 1.1.8

    我无法理解 Knuth 在第 1 1 章练习 8 的说明中的含义 任务是制定一个有效的两个正整数的 gcd 算法m and n使用他的符号theta j phi j b j and a j 其中 theta 和 phi 是字符串 a and
  • 如何访问 Mercurial 进程内挂钩中的提交消息?

    我一直在努力 def debug hook ui repo kwargs changectx repo None ui status change desc s n changectx description return True 但它总
  • 通过 Emacs 启动时如何配置 SBCL 以使用更多 RAM?

    如何配置 SBCL 使其在使用 Emacs 中的 M x slime 启动时使用比默认值更多的内存 从我在网上看到的情况来看 答案似乎是调用 SBCL 传递参数 dynamic space size 由于我不直接调用 SBCL 因此我不知道
  • FPDF 和欧元符号的问题

    我花了几天时间筛选各种方法来鼓励 FPDF 渲染欧元符号 但没有成功 我有 currency iconv UTF 8 ISO 8859 1 TRANSLIT 结果是 iconv function iconv 检测到不完整的多字节字符 在输入
  • 在滚动视图上拖动视图:收到touchesBegan,但未收到touchesEnded 或touchesCancelled

    作为一名 iOS 编程新手 我正在努力解决iPhone 上的文字游戏 https github com afarber ios newbie tree master ScrollContent 应用程序结构是 scrollView gt c
  • 如何设置dropdownlist高度以及如何显示dropdownlist列表始终向下显示

    如何在 C 中设置下拉列表控件的高度 我尝试了这个 但它不起作用 cbo Attributes Add style height 50 而且 如何确保下拉列表的列表始终向下而不是向上 终于我明白了 cbo Height new Unit 2
  • Python - 读取 Emoji Unicode 字符

    我有一个 Python 2 7 程序 它从 SQLite 数据库读取 iOS 文本消息 文本消息是 unicode 字符串 在下面的短信中 u that u2019s U0001f63b 撇号表示为 u2019 但表情符号由 U0001f6
  • 具有 GIT 支持的 PL/SQL IDE

    我目前正在为我的公司开发 PL SQL 存储过程 我想使用代码修订控制系统来跟踪我和其他开发人员所做的更改 我喜欢 GIT 的所有优点 包括分布式 scm 功能 有没有支持GIT的PL SQL开发IDE 目前 我正在使用 JDevelope
  • 从 C# 调用非托管函数:我应该传递 StringBuilder 还是使用不安全代码?

    我有一个 C 程序 需要将字符缓冲区传递给非托管函数 我发现了两种似乎可靠的方法 但我不确定应该选择哪一种 这是非托管函数的签名 extern C declspec dllexport int getNextResponse char bu
  • 关于 C++ 中异常的缺点

    我正在阅读 Google C 风格指南 并在其中感到困惑例外情况 http google styleguide googlecode com svn trunk cppguide xml showone Exceptions Excepti
  • XPath 中“//”和“/”的区别?

    我正在尝试使用 python selenium 的 XPath I used 这个链接 http www jetairways com EN SG Home aspx尝试教程中的一些 XPath 所以我尝试了 XPath 的这两种变体 这个
  • Vuejs 刷新时路由重定向

    当我在浏览器中使用刷新按钮或点击f5在键盘上 它不会刷新我的页面 而是重定向到主页 Code router js import Vue from vue import VueRouter from vue router import sto
  • 接口依赖关系[关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 当您创建一个接口并且知道您将依赖另一个接口时 您是否会将构造函数作为接口的一部分 就我而言 我想创建 我可以向客户端提供一个 IClientRe
  • 伊莎贝尔案例分析

    如何在伊莎贝尔中应用案例分析 我正在寻找类似的东西apply induct x 用于归纳 案例分析通常是通过cases方法 另见索引中的 案例 方法 伊莎贝尔 伊萨尔参考手册 http isabelle in tum de website
  • 使用 grep 列出目录中的条目

    我试图列出目录中名称仅包含大写字母的所有条目 目录需要附加 bin bash cd testfiles ls grep r 由于 grep 默认情况下仅查找大写字母 对吗 因此我只是在 testfiles 下的目录中递归搜索仅包含大写字母的
  • 将 nlog 中的记录添加到 dataType = date 的字段

    I use nlogdll 写入数据库 Oracle 与实体框架在行中 logger Log logLevel try 我在 nlog 日志中收到以下错误 文字与模板字符串不匹配 代码是 SetPropGDC LogEntity NLog
  • 在 Windows 上使用 Xerces 3.0.1 和 C++ 编写 XML

    我编写了以下函数来使用 Xerces 3 0 1 创建 XML 文件 如果我使用 foo xml 或 foo xml 的文件路径调用此函数 它会很好用 但如果我传入 c foo xml 然后我在这一行得到一个异常 XMLFormatTarg