EscapeXML C ++ Visual Studio

时间:2016-05-04 20:44:30

标签: c++ xml visual-studio

我想在Visual Studio C ++上转换EscapeXML的特殊字符。

#include "stdafx.h"
#include "atlenc.h";
#include <string>
#include <iostream>
using namespace std;


int main()
{
    std::string test = "& & &";

    inline int EscapeXML(const wchar_t * test)throw();

    cout << test;
    return 0;
}

我想要输出。

&amp; &amp; &amp;

Visual Studio具有EscapeXML功能,但它不会转换。 https://msdn.microsoft.com/en-us/library/y0y57exc(v=vs.71).aspx

1 个答案:

答案 0 :(得分:1)

您的代码有几个问题。首先,你不应该用分号结束#include指令。

那就是说,主要的问题是你的代码没有调用EscapeXML,它实际上正在重新定义它。你想要的是这样的:

#include "stdafx.h"
#include "atlenc.h"
#include <string>
#include <iostream>

int main()
{
    std::wstring test = L"& & &";

    int output_size = EscapeXML(test.c_str(), test.length(), 0, 0, ATL_ESC_FLAG_ATTR);

    std::wstring testout;
    testout.resize(output_size);
    EscapeXML(test.c_str(), test.length(), &testout[0], output_size, ATL_ESC_FLAG_ATTR);

    std::wcout << testout;
    return 0;
}

请注意,EscapeXML需要一个指向宽字符串(wchar_t *)的指针,因此您需要使用std :: wstring(和std:wcout)。您需要将输入字符串和缓冲区都传递给它,它可以写入“转义”版本。

由于我们事先并不知道缓冲区需要多大,我们使用空指针调用EscapeXML - 大多数返回字符串的Windows API函数都可以执行此操作,并且它们将返回所需的缓冲区大小。然后我们实例化另一个wstring,将其大小调整为所需的大小,然后再次调用EscapeXML,这次实际上将指针传递给缓冲区。实际上,由于c_str()返回一个const指针(我们无法传递给期望非const指针的函数,除非我们使用const_cast),我们改为将指针传递给testout [0],这是一个开始wstring的内部字符串缓冲区。