Xerces 序列化XML

前端之家收集整理的这篇文章主要介绍了Xerces 序列化XML前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

今天继续学习Xerces序列化XML,保存到xml文件和打印。

class XmlSerializer

{

public:

XmlSerializer();

~XmlSerializer();

voidAddNode(string nodeName,string nodeValue);

voidSave(string fileName);

voidPrint();

voidCreateDocument(string rootName);

protected:

private:

DOMDocument *m_pDocument;

DOMNode *m_pCurNode;

DOMNode *m_pRootNode;

DOMLSSerializer *m_pSerializer;

DOMImplementation *m_pImpl;

};

XmlSerializer::XmlSerializer()

{

XMLCh tempStr[100];

XMLString::transcode("LS",tempStr,99);

m_pImpl =DOMImplementationRegistry::getDOMImplementation(tempStr);

m_pSerializer =((DOMImplementationLS*)m_pImpl)->createLSSerializer();

XMLString::transcode("range",99);

DOMImplementation* impl =DOMImplementationRegistry::getDOMImplementation(tempStr);

}

XmlSerializer::~XmlSerializer()

{

m_pSerializer->release();

}

voidXmlSerializer::AddNode( string nodeName,string nodeValue )

{

if(m_pDocument)

{

DOMElement *pElement =m_pDocument->createElement(XMLString::transcode(nodeName.c_str()));

DOMText *pTextNode =m_pDocument->createTextNode(XMLString::transcode(nodeValue.c_str()));

pElement->appendChild(pTextNode);

m_pCurNode->appendChild(pElement);

}

}

voidXmlSerializer::Save( string fileName )

{

XMLCh tempStr[100];

XMLString::transcode(fileName.c_str(),99);

m_pSerializer->writeToURI(m_pDocument,tempStr/*XMLString::transcode(fileName.c_str)*/);

}

voidXmlSerializer::Print()

{

if(m_pSerializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTDiscardDefaultContent,true))

m_pSerializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTDiscardDefaultContent,true);

if(m_pSerializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint,true))

m_pSerializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint,true);

XMLFormatTarget *myFormTarget = new StdOutFormatTarget();

DOMLSOutput* theOutput =((DOMImplementationLS*)m_pImpl)->createLSOutput();

theOutput->setByteStream(myFormTarget);

m_pSerializer->write(m_pDocument,theOutput);

theOutput->release();

deletemyFormTarget;

}

voidXmlSerializer::CreateDocument( string rootName )

{

XMLCh tempStr[100];

XMLString::transcode(rootName.c_str(),99);

m_pDocument = m_pImpl->createDocument(0,0);

m_pRootNode =m_pDocument->getDocumentElement();

m_pCurNode = m_pRootNode;

}

int main(int argc,char*argv[])

{

try

{

XMLPlatformUtils::Initialize();

cout<<"Initialize success..."<<endl;

XmlSerializer *pserializer = new XmlSerializer;

pserializer->CreateDocument("Book");

pserializer->AddNode("Name","C++");

pserializer->AddNode("price","69.5");

pserializer->AddNode("writer","hhh");

pserializer->Print();

pserializer->Save("Book.xml");

}

catch (const XMLException& toCatch)

{

return 1;

}

XMLPlatformUtils::Terminate();

system("pause");

return 0;

}

原文链接:https://www.f2er.com/xml/299136.html

猜你在找的XML相关文章