Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使XMLDOMDocument包含XML声明?_Xml_Dom_Msxml - Fatal编程技术网

如何使XMLDOMDocument包含XML声明?

如何使XMLDOMDocument包含XML声明?,xml,dom,msxml,Xml,Dom,Msxml,当XMLDOMDocument保存自身时,如何使其包含XML声明,例如: 正在内存中创建XmlDomDocument对象(即,未从某些外部源加载xml): 如果没有xml声明,则只能获取正文xml,例如: <Customer> ... </Customer> ... 而不是完整的XML文档: <?xml version="1.0" encoding="US-ASCII" ?> <Customer> ...

当XMLDOMDocument保存自身时,如何使其包含XML声明,例如:

正在内存中创建XmlDomDocument对象(即,未从某些外部源加载xml):

如果没有xml声明,则只能获取正文xml,例如:

<Customer>
   ...
</Customer>

...
而不是完整的XML文档:

<?xml version="1.0" encoding="US-ASCII" ?>
<Customer>
   ...
</Customer>

...
问题2
如何控制保存到流时将使用的?

您需要使用MXXMLWriter60,而不是直接保存。很抱歉,我没有一个C#示例,但这里是与VB.Net等效的。有关详细信息,请参阅

' Create and load a DOMDocument object.

Dim xmlDoc As New DOMDocument60
xmlDoc.loadXML("<doc><one>test1</one><two>test2</two></doc>")

' Set properties on the XML writer - including BOM, XML declaration and encoding

Dim wrt As New MXXMLWriter60
wrt.byteOrderMark = True
wrt.omitXMLDeclaration = False
wrt.encoding = "US-ASCII"
wrt.indent = True

' Set the XML writer to the SAX content handler.

Dim rdr As New SAXXMLReader60
Set rdr.contentHandler = wrt
Set rdr.dtdHandler = wrt
Set rdr.errorHandler = wrt
rdr.putProperty "http://xml.org/sax/properties/lexical-handler", wrt
rdr.putProperty "http://xml.org/sax/properties/declaration-handler", wrt

' Now pass the DOM through the SAX handler, and it will call the writer

rdr.parse xmlDoc

' Let the writer do its thing

Dim iFileNo As Integer
iFileNo = FreeFile
Open App.Path + "\saved.xml" For Output As #iFileNo
Print #iFileNo, wrt.output
Close #iFileNo
创建并加载DOMDocument对象。 Dim xmlDoc作为新的DOMDocument60 loadXML(“test1test2”) '在XML编写器上设置属性-包括BOM表、XML声明和编码 Dim wrt作为新的MXXMLWriter60 wrt.byteOrderMark=True wrt.omitXMLDeclaration=False wrt.encoding=“US-ASCII” wrt.indent=True '将XML编写器设置为SAX内容处理程序。 Dim rdr作为新的SAXXMLReader60 设置rdr.contentHandler=wrt 设置rdr.dtdHandler=wrt 设置rdr.errorHandler=wrt rdr.putProperty“http://xml.org/sax/properties/lexical-handler“,wrt rdr.putProperty“http://xml.org/sax/properties/declaration-handler“,wrt '现在通过SAX处理程序传递DOM,它将调用编写器 解析xmlDoc “让作者自己做吧 Dim iFileNo作为整数 iFileNo=FreeFile 打开App.Path+“\saved.xml”,输出为#iFileNo 打印#iFileNo,wrt.output 关闭#iFileNo 这里是c语言中的++

bool-PPrintDOMDocument(IXMLDOMDocument*pDoc、IStream*pStream)
{
//创造作家
电脑打印机;
CHK_失败(pMXWriter.CoCreateInstance(uuuidof(MXXMLWriter),NULL,CLSCTX_ALL));
CComPtr pISAXContentHandler;
CHK_失败(pMXWriter.QueryInterface(&pISAXContentHandler));
首席执行官pISAXErrorHandler;
CHK_失败(pMXWriter.QueryInterface(&pISAXErrorHandler));
pISAXDTDHandler先生;
CHK_失败(pMXWriter.QueryInterface(&pISAXDTDHandler));
CHK_失败(pMXWriter->put_省略xmlsdeclaration(VARIANT_FALSE));
CHK_失败(pMXWriter->put_standalone(VARIANT_TRUE));
CHK_失败(pMXWriter->put_indent(VARIANT_TRUE));
CHK_失败(pMXWriter->put_编码(L“UTF-8”);
诗篇阅读器;
CHK_失败(pSAXReader.CoCreateInstance(uu_uidof(SAXXMLReader),NULL,CLSCTX_ALL));
CHK_失败(pSAXReader->putContentHandler(pISAXContentHandler));
CHK_失败(pSAXReader->puttdhandler(pISAXDTDHandler));
CHK_失败(pSAXReader->putErrorHandler(pISAXErrorHandler));
CHK_失败(pSAXReader->putProperty(
L“http://xml.org/sax/properties/lexical-handler,CComVariant(pMXWriter));
CHK_失败(pSAXReader->putProperty(
L“http://xml.org/sax/properties/declaration-handler,CComVariant(pMXWriter));
如果(!successed(pMXWriter->put_output(CComVariant(pStream)))返回false;
如果(!successed(pSAXReader->parse(CComVariant(pDoc)))返回false;
pMXWriter->flush();
}
…你需要一个合适的

//实现从IStream派生的文件流
类FileStream:公共IStream
{
文件流(句柄文件)
{
_refcount=1;
_hFile=hFile;
}
~FileStream()
{
if(\u hFile!=无效的\u句柄\u值)
{
::闭合手柄(_hFile);
}
}
公众:
HRESULT静态开放文件(LPCWSTR pName、IStream**ppStream、bool-fWrite)
{
HANDLE hFile=::CreateFileW(pName,
fWrite?GENERIC_WRITE:GENERIC_READ,FILE_SHARE_READ,
无效的
fWrite?始终创建:打开现有的,
文件\u属性\u正常,
无效);
if(hFile==无效的句柄值)
从_WIN32返回HRESULT_(GetLastError());
*ppStream=新文件流(hFile);
如果(*ppStream==NULL)
闭合手柄(hFile);
返回S_OK;
}
虚拟HRESULT STDMETHODCALLTYPE查询接口(refid iid,void**ppvoObject)
{ 
如果(iid==\uuuuIdof(IUnknown)
||iid==\uuuuIdof(IStream)
||iid==(等序流)
{
*ppvObject=静态投影(此);
AddRef();
返回S_OK;
}否则
返回E_NOINTERFACE;
}
虚拟ULONG标准方法调用类型AddRef(无效)
{ 
返回(ULONG)联锁增量(&_refcount);
}
虚拟ULONG标准方法调用类型发布(无效)
{
ULONG res=(ULONG)联锁减量(&_refcount);
如果(res==0)
删除此项;
返回res;
}
//等序流接口
公众:
虚拟HRESULT STDMETHODCALLTYPE读取(void*pv、ULONG cb、ULONG*pcbRead)
{
BOOL rc=ReadFile(_hFile,pv,cb,pcbRead,NULL);
返回(rc)?S_确定:HRESULT_FROM_WIN32(GetLastError());
}
虚拟HRESULT STDMETHODCALLTYPE写入(void const*pv、ULONG cb、ULONG*pcbcwrite)
{
BOOL rc=WriteFile(_hFile,pv,cb,pcbswrited,NULL);
返回rc?S_OK:HRESULT_FROM_WIN32(GetLastError());
}
//IStream接口
公众:
虚拟HRESULT STDMETHODCALLTYPE设置大小(ULARGE_整数)
{ 
返回E_NOTIMPL;
}
虚拟HRESULT STDMETHODCALLTYPE CopyTo(IStream*、ULARGE\u INTEGER、ULARGE\u INTEGER*,
ULARGE_整数*)
{ 
返回E_NOTIMPL;
}
虚拟HRESULT STDMETHODCALLTYPE提交(DWORD)
{ 
返回E_NOTIMPL;
}
虚拟HRESULT STDMETHODCALLTYPE还原(无效)
{ 
返回E_NOTIMPL;
}
' Create and load a DOMDocument object.

Dim xmlDoc As New DOMDocument60
xmlDoc.loadXML("<doc><one>test1</one><two>test2</two></doc>")

' Set properties on the XML writer - including BOM, XML declaration and encoding

Dim wrt As New MXXMLWriter60
wrt.byteOrderMark = True
wrt.omitXMLDeclaration = False
wrt.encoding = "US-ASCII"
wrt.indent = True

' Set the XML writer to the SAX content handler.

Dim rdr As New SAXXMLReader60
Set rdr.contentHandler = wrt
Set rdr.dtdHandler = wrt
Set rdr.errorHandler = wrt
rdr.putProperty "http://xml.org/sax/properties/lexical-handler", wrt
rdr.putProperty "http://xml.org/sax/properties/declaration-handler", wrt

' Now pass the DOM through the SAX handler, and it will call the writer

rdr.parse xmlDoc

' Let the writer do its thing

Dim iFileNo As Integer
iFileNo = FreeFile
Open App.Path + "\saved.xml" For Output As #iFileNo
Print #iFileNo, wrt.output
Close #iFileNo
bool PPrintDOMDocument (IXMLDOMDocument* pDoc, IStream* pStream)
{
    // Create the writer
    CComPtr <IMXWriter> pMXWriter;
    CHK_FAILED(pMXWriter.CoCreateInstance(__uuidof (MXXMLWriter), NULL, CLSCTX_ALL));

    CComPtr <ISAXContentHandler> pISAXContentHandler;
    CHK_FAILED (pMXWriter.QueryInterface(&pISAXContentHandler));

    CComPtr <ISAXErrorHandler> pISAXErrorHandler;
    CHK_FAILED(pMXWriter.QueryInterface (&pISAXErrorHandler));

    CComPtr <ISAXDTDHandler> pISAXDTDHandler;
    CHK_FAILED (pMXWriter.QueryInterface (&pISAXDTDHandler));

    CHK_FAILED (pMXWriter->put_omitXMLDeclaration (VARIANT_FALSE));
    CHK_FAILED (pMXWriter->put_standalone (VARIANT_TRUE));
    CHK_FAILED (pMXWriter->put_indent (VARIANT_TRUE));
    CHK_FAILED (pMXWriter->put_encoding (L"UTF-8"));

    CComPtr <ISAXXMLReader> pSAXReader;
    CHK_FAILED (pSAXReader.CoCreateInstance (__uuidof (SAXXMLReader), NULL, CLSCTX_ALL));

    CHK_FAILED (pSAXReader ->putContentHandler (pISAXContentHandler));
    CHK_FAILED (pSAXReader ->putDTDHandler (pISAXDTDHandler));
    CHK_FAILED (pSAXReader ->putErrorHandler (pISAXErrorHandler));
    CHK_FAILED (pSAXReader ->putProperty (
      L"http://xml.org/sax/properties/lexical-handler", CComVariant (pMXWriter)));
    CHK_FAILED (pSAXReader ->putProperty (
      L"http://xml.org/sax/properties/declaration-handler", CComVariant (pMXWriter)));

    if (! SUCCEEDED (pMXWriter ->put_output (CComVariant (pStream)))) return false;
    if (! SUCCEEDED (pSAXReader->parse(CComVariant (pDoc)))) return false;
    pMXWriter->flush();
}
//implement filestream that derives from IStream
class FileStream : public IStream
{
    FileStream(HANDLE hFile) 
    {
        _refcount = 1;
        _hFile = hFile;
    }

    ~FileStream()
    {
        if (_hFile != INVALID_HANDLE_VALUE)
        {
            ::CloseHandle(_hFile);
        }
    }

public:
    HRESULT static OpenFile(LPCWSTR pName, IStream ** ppStream, bool fWrite)
    {
        HANDLE hFile = ::CreateFileW(pName, 
            fWrite ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ,
            NULL, 
            fWrite ? CREATE_ALWAYS : OPEN_EXISTING, 
            FILE_ATTRIBUTE_NORMAL, 
            NULL);

        if (hFile == INVALID_HANDLE_VALUE)
            return HRESULT_FROM_WIN32(GetLastError());

        *ppStream = new FileStream(hFile);

        if(*ppStream == NULL)
            CloseHandle(hFile);

        return S_OK;
    }

    virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void ** ppvObject)
    { 
        if (iid == __uuidof(IUnknown)
            || iid == __uuidof(IStream)
            || iid == __uuidof(ISequentialStream))
        {
            *ppvObject = static_cast<IStream*>(this);
            AddRef();
            return S_OK;
        } else
            return E_NOINTERFACE; 
    }

    virtual ULONG STDMETHODCALLTYPE AddRef(void) 
    { 
        return (ULONG)InterlockedIncrement(&_refcount); 
    }

    virtual ULONG STDMETHODCALLTYPE Release(void) 
    {
        ULONG res = (ULONG) InterlockedDecrement(&_refcount);
        if (res == 0) 
            delete this;
        return res;
    }

    // ISequentialStream Interface
public:
    virtual HRESULT STDMETHODCALLTYPE Read(void* pv, ULONG cb, ULONG* pcbRead)
    {
        BOOL rc = ReadFile(_hFile, pv, cb, pcbRead, NULL);
        return (rc) ? S_OK : HRESULT_FROM_WIN32(GetLastError());
    }

    virtual HRESULT STDMETHODCALLTYPE Write(void const* pv, ULONG cb, ULONG* pcbWritten)
    {
        BOOL rc = WriteFile(_hFile, pv, cb, pcbWritten, NULL);
        return rc ? S_OK : HRESULT_FROM_WIN32(GetLastError());
    }

    // IStream Interface
public:
    virtual HRESULT STDMETHODCALLTYPE SetSize(ULARGE_INTEGER)
    { 
        return E_NOTIMPL;   
    }

    virtual HRESULT STDMETHODCALLTYPE CopyTo(IStream*, ULARGE_INTEGER, ULARGE_INTEGER*,
        ULARGE_INTEGER*) 
    { 
        return E_NOTIMPL;   
    }

    virtual HRESULT STDMETHODCALLTYPE Commit(DWORD)                                      
    { 
        return E_NOTIMPL;   
    }

    virtual HRESULT STDMETHODCALLTYPE Revert(void)                                       
    { 
        return E_NOTIMPL;   
    }

    virtual HRESULT STDMETHODCALLTYPE LockRegion(ULARGE_INTEGER, ULARGE_INTEGER, DWORD)              
    { 
        return E_NOTIMPL;   
    }

    virtual HRESULT STDMETHODCALLTYPE UnlockRegion(ULARGE_INTEGER, ULARGE_INTEGER, DWORD)            
    { 
        return E_NOTIMPL;   
    }

    virtual HRESULT STDMETHODCALLTYPE Clone(IStream **)                                  
    { 
        return E_NOTIMPL;   
    }

    virtual HRESULT STDMETHODCALLTYPE Seek(LARGE_INTEGER liDistanceToMove, DWORD dwOrigin,
        ULARGE_INTEGER* lpNewFilePointer)
    { 
        DWORD dwMoveMethod;

        switch(dwOrigin)
        {
        case STREAM_SEEK_SET:
            dwMoveMethod = FILE_BEGIN;
            break;
        case STREAM_SEEK_CUR:
            dwMoveMethod = FILE_CURRENT;
            break;
        case STREAM_SEEK_END:
            dwMoveMethod = FILE_END;
            break;
        default:   
            return STG_E_INVALIDFUNCTION;
            break;
        }

        if (SetFilePointerEx(_hFile, liDistanceToMove, (PLARGE_INTEGER) lpNewFilePointer,
                             dwMoveMethod) == 0)
            return HRESULT_FROM_WIN32(GetLastError());
        return S_OK;
    }

    virtual HRESULT STDMETHODCALLTYPE Stat(STATSTG* pStatstg, DWORD grfStatFlag) 
    {
        if (GetFileSizeEx(_hFile, (PLARGE_INTEGER) &pStatstg->cbSize) == 0)
            return HRESULT_FROM_WIN32(GetLastError());
        return S_OK;
    }

private:
    HANDLE _hFile;
    LONG _refcount;
};
//writes the document to the WideString as UTF-16 (since it's a WideString)
class function TXMLHelper.WriteDocumentToString(
       const Document60: DOMDocument60): WideString; 
var
    writer: IMXWriter;
    reader: IVBSAXXMLReader;
    bstr: OleVariant;
begin
{
    From http://support.microsoft.com/kb/275883
    INFO: XML Encoding and DOM Interface Methods

    MSXML has native support for the following encodings:
        UTF-8
        UTF-16
        UCS-2
        UCS-4
        ISO-10646-UCS-2
        UNICODE-1-1-UTF-8
        UNICODE-2-0-UTF-16
        UNICODE-2-0-UTF-8

    It also recognizes (internally using the WideCharToMultibyte 
    API function for mappings) the following encodings:
        US-ASCII
        ISO-8859-1
        ISO-8859-2
        ISO-8859-3
        ISO-8859-4
        ISO-8859-5
        ISO-8859-6
        ISO-8859-7
        ISO-8859-8
        ISO-8859-9
        WINDOWS-1250
        WINDOWS-1251
        WINDOWS-1252
        WINDOWS-1253
        WINDOWS-1254
        WINDOWS-1255
        WINDOWS-1256
        WINDOWS-1257
        WINDOWS-1258
}

    if Document60 = nil then
       raise Exception.Create('TXMLHelper.WriteDocument: Document60 cannot be nil');

    // Set properties on the XML writer
    //    - including BOM, XML declaration and encoding
    writer := CoMXXMLWriter60.Create;
    writer.byteOrderMark := False; //Don't write the BOM. Has no effect for BSTR output, but still: we don't want it.  Determines whether to write the Byte Order Mark (BOM). The byteOrderMark property has no effect for BSTR or DOM output. (Default True)
    writer.omitXMLDeclaration := False; //Don't skip the xml declaration.   Forces the IMXWriter to skip the XML declaration. Useful for creating document fragments. (Default False)
//  writer.encoding := 'UTF-8'; //Sets and gets encoding for the output. (Default "UTF-16")
    writer.indent := True; //Sets whether to indent output. (Default False)
    writer.standalone := True; //Sets the value of the standalone attribute in the XML declaration to "yes" or "no".


    // Set the XML writer to the SAX content handler.
    reader := CoSAXXMLReader60.Create;
    reader.contentHandler := writer as IVBSAXContentHandler;
    reader.dtdHandler := writer as IVBSAXDTDHandler;
    reader.errorHandler := writer as IVBSAXErrorHandler;
    reader.putProperty('http://xml.org/sax/properties/lexical-handler', writer);
    reader.putProperty('http://xml.org/sax/properties/declaration-handler', writer);

    // Now pass the DOM through the SAX handler, and it will call the writer
    reader.parse(Document60);

    // Let the writer do its thing
    bstr := writer.output;
    Result := bstr;
end;
class procedure TXMLHelper.WriteDocumentToStream(const Document60: DOMDocument60; const stream: IStream; Encoding: string);
var
    writer: IMXWriter;
    reader: IVBSAXXMLReader;
begin
{
    From http://support.microsoft.com/kb/275883
    INFO: XML Encoding and DOM Interface Methods

    MSXML has native support for the following encodings:
        UTF-8
        UTF-16
        UCS-2
        UCS-4
        ISO-10646-UCS-2
        UNICODE-1-1-UTF-8
        UNICODE-2-0-UTF-16
        UNICODE-2-0-UTF-8

    It also recognizes (internally using the WideCharToMultibyte API function for mappings) the following encodings:
        US-ASCII
        ISO-8859-1
        ISO-8859-2
        ISO-8859-3
        ISO-8859-4
        ISO-8859-5
        ISO-8859-6
        ISO-8859-7
        ISO-8859-8
        ISO-8859-9
        WINDOWS-1250
        WINDOWS-1251
        WINDOWS-1252
        WINDOWS-1253
        WINDOWS-1254
        WINDOWS-1255
        WINDOWS-1256
        WINDOWS-1257
        WINDOWS-1258
}

    if Document60 = nil then
        raise Exception.Create('TXMLHelper.WriteDocument: Document60 cannot be nil');
    if stream = nil then
        raise Exception.Create('TXMLHelper.WriteDocument: stream cannot be nil');

    // Set properties on the XML writer - including BOM, XML declaration and encoding
    writer := CoMXXMLWriter60.Create;
    writer.byteOrderMark := True; //Determines whether to write the Byte Order Mark (BOM). The byteOrderMark property has no effect for BSTR or DOM output. (Default True)
    writer.omitXMLDeclaration := False; //Forces the IMXWriter to skip the XML declaration. Useful for creating document fragments. (Default False)
    if Encoding <> '' then
        writer.encoding := Encoding; //Sets and gets encoding for the output. (Default "UTF-16")
    writer.indent := True; //Sets whether to indent output. (Default False)
    writer.standalone := True;

    // Set the XML writer to the SAX content handler.
    reader := CoSAXXMLReader60.Create;
    reader.contentHandler := writer as IVBSAXContentHandler;
    reader.dtdHandler := writer as IVBSAXDTDHandler;
    reader.errorHandler := writer as IVBSAXErrorHandler;
    reader.putProperty('http://xml.org/sax/properties/lexical-handler', writer);
    reader.putProperty('http://xml.org/sax/properties/declaration-handler', writer);


    writer.output := stream; //The resulting document will be written into the provided IStream

    // Now pass the DOM through the SAX handler, and it will call the writer
    reader.parse(Document60);

    writer.flush;
end;
' Create and load a DOMDocument object.

Dim xmlDoc As New DOMDocument
Dim xRecords As IXMLDOMElement

' Make the Records the root node and add instructional line to XML file.
Set xRecords = xmlDoc.createElement("HeuristicFiler")
xmlDoc.appendChild xmlDoc.createProcessingInstruction("xml", "version=""1.0"" encoding=""UTF-8"" standalone=""yes""")
xmlDoc.appendChild xRecords

'  Add various records

' Save the XML File 
xmlDoc.Save strFilePath
std::string xmlString = ...
xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + xmlString