-- 作者:fwycome
-- 发布时间:5/9/2007 10:48:00 AM
-- 用Dom生成xml文档,可换行缩近,不会产生 xmlns="" 属性
void SaveXml() { HRESULT hr; IXMLDOMDocumentPtr xmlFile; hr = xmlFile.CreateInstance(__uuidof(DOMDocument40)); if( FAILED(hr) ) { OutputXmlErr(); return; } MSXML2::IXMLDOMProcessingInstructionPtr pProcessingInstruction; pProcessingInstruction = xmlFile->createProcessingInstruction(_bstr_t("xml"), _bstr_t("version=\"1.0\" encoding = \"utf-8\"")); xmlFile->appendChild((IXMLDOMNodePtr) pProcessingInstruction); IXMLDOMTextPtr ptrText = NULL; _bstr_t attrName = _T(""); _variant_t attrVal = _T(""); _bstr_t text; const _bstr_t bstrDefNs = _T("http://www.w3.org/2000/svg"); _variant_t nodetype = long(NODE_ELEMENT); //创建根节点 _bstr_t name = _T("svg"); IXMLDOMElementPtr pXmlRoot = xmlFile->createElement(name); if( pXmlRoot == NULL ) return; pXmlRoot = xmlFile->appendChild(pXmlRoot); //给根节点添加属性 attrName = _T("width"); attrVal = float(500); pXmlRoot->setAttribute(attrName, attrVal); attrName = _T("height"); attrVal = float(400); pXmlRoot->setAttribute(attrName, attrVal); attrName = _T("xmlns"); pXmlRoot->setAttribute(attrName, bstrDefNs); attrName = _T("xmlns:xlink"); attrVal = _T("http://www.w3.org/1999/xlink"); pXmlRoot->setAttribute(attrName, attrVal); //pXmlRoot 中添加 pNewText 节点 text = _T("\n\t"); ptrText = xmlFile->createTextNode(text); pXmlRoot->appendChild(ptrText); name = _T("家禽"); IXMLDOMCommentPtr pNewText = xmlFile->createComment(name); pXmlRoot->appendChild(pNewText); //pXmlRoot 中添加 pNewElm节点 text = _T("\n\t"); ptrText = xmlFile->createTextNode(text); pXmlRoot->appendChild(ptrText); name = _T("g"); nodetype = long(NODE_ELEMENT); IXMLDOMElementPtr pNewElm = xmlFile->createNode(nodetype,name,bstrDefNs); pXmlRoot->appendChild(pNewElm); //pNewElm 中添加 text节点 name = _T("\n\t\t"); ptrText = xmlFile->createTextNode(name); pNewElm->appendChild(ptrText); name = _T("text"); nodetype = long(NODE_ELEMENT); IXMLDOMElementPtr pNewGChld = xmlFile->createNode(nodetype,name,bstrDefNs); pNewElm->appendChild(pNewGChld); name = _T("\n\t"); ptrText = xmlFile->createTextNode(name); pNewElm->appendChild(ptrText); attrName = _T("x"); attrVal = float(20); pNewGChld->setAttribute( attrName, attrVal ); attrName = _T("y"); attrVal = float(30); pNewGChld->setAttribute( attrName, attrVal ); attrName = _T("fill"); attrVal = _T("#00007f"); pNewGChld->setAttribute( attrName, attrVal ); attrName = _T("font-family"); attrVal = _T("宋体"); pNewGChld->setAttribute( attrName, attrVal ); attrName = _T("font-size"); attrVal = float(20); pNewGChld->setAttribute( attrName, attrVal ); text = _T("\n\t\t\t你好,鸭子!\n\t\t"); pNewGChld->put_text( text ); text = _T("\n"); ptrText = xmlFile->createTextNode(text); pXmlRoot->appendChild(ptrText); _variant_t szPath = _T("F:\\VC\\信息子站\\Doc\\代码示例\\SvgDra1.svg"); hr = xmlFile->save(szPath); if( FAILED(hr) ) { OutputXmlErr(); return; } }
|