使用 XmlLite IXmlWriter (C++) 在 prolog 中创建没有编码属性的 XML

Creating XML without encoding attribute in prolog using XmlLite IXmlWriter (C++)

我正在使用 XmlLite 库创建一个 XML 文件。我希望生成的 XML 文件的序言不包含编码属性(仅包含版本):

<?xml version="1.0"?>

这是我的代码:

    HRESULT hr = S_OK;
    IStream *pOutFileStream = NULL;
    IXmlWriter *pWriter = NULL;
    CComPtr<IXmlWriterOutput> pWriterOutput;

    //Open writeable output stream
    if (FAILED(hr = SHCreateStreamOnFile(output_file_name, STGM_CREATE | STGM_WRITE, &pOutFileStream)))
    {
        wprintf(L"Error creating file writer, error is %08.8lx", hr);
        HR(hr);
    }

    if (FAILED(hr = CreateXmlWriter(__uuidof(IXmlWriter), (void**) &pWriter, NULL)))
    {
        wprintf(L"Error creating xml writer, error is %08.8lx", hr);
        HR(hr);
    }

    if(FAILED(CreateXmlWriterOutputWithEncodingName(pOutFileStream, NULL, L"UTF-8", &pWriterOutput))){
        wprintf(L"Error setting xml encoding, error is %08.8lx", hr);
        HR(hr);
    }

    if (FAILED(hr = pWriter->SetOutput(pWriterOutput)))
    {
        wprintf(L"Error, Method: SetOutput, error is %08.8lx", hr);
        HR(hr);
    }

    if (FAILED(hr = pWriter->SetProperty(XmlWriterProperty_Indent, 4)))
    {
        wprintf(L"Error, Method: SetProperty XmlWriterProperty_Indent, error is %08.8lx", hr);
        HR(hr);
    }

    if (FAILED(hr = pWriter->WriteStartDocument(XmlStandalone_Omit)))
    {
        wprintf(L"Error, Method: WriteStartDocument, error is %08.8lx", hr);
        HR(hr);
    } 

我已经尝试删除对 CreateXmlWriterOutputWithEncodingName() 的调用,但即便如此,也会创建一个带有 UTF-8 的默认编码属性。 我还尝试将 NULL 作为该函数的第三个参数。

非常感谢您的帮助!

XML声明是由WriteStartDocument method写的。

你可以用L"xml"作为处理指令的名称调用WriteProcessingInstruction,而不是调用WriteStartDocument,以按照你想要的方式编写XML声明,因为示例:

if (FAILED(hr = pWriter->WriteProcessingInstruction(L"xml", L"version=\"1.0\"")))
{
    wprintf(L"Error, Method: WriteProcessingInstruction, error is %08.8lx", hr); 
    HR(hr); 
}

这会将 XML 声明写成 <?xml version="1.0"?>