この例ではDOMを使ってparamというタグにnameとvalueというアトリビュートを持たせてパラメータ設定に使えるようなXMLを作成し、そのDOMドキュメントを書き出しています。
動作確認したバージョンはXerces 3.1.1です。
Source Code
#include <iostream>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/framework/LocalFileFormatTarget.hpp>
XERCES_CPP_NAMESPACE_USE
void OutputXML(xercesc::DOMDocument* pmyDOMDocument, const char *filePath)
{
DOMImplementation *implementation = DOMImplementationRegistry::getDOMImplementation(L"LS");
DOMLSSerializer *serializer = ((DOMImplementationLS*)implementation)->createLSSerializer();
if (serializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true)){
serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);
}
serializer->setNewLine(XMLString::transcode("\r\n"));
//** Convert the path into Xerces compatible XMLCh*.
XMLCh *tempFilePath = XMLString::transcode(filePath);
//** Specify the target for the XML output.
XMLFormatTarget *formatTarget = new LocalFileFormatTarget(tempFilePath);
//** Create a new empty output destination object.
DOMLSOutput *output = ((DOMImplementationLS*)implementation)->createLSOutput();
//** Set the stream to our target.
output->setByteStream(formatTarget);
//** Write the serialized output to the destination.
serializer->write(pmyDOMDocument, output);
//** Cleanup
serializer->release();
XMLString::release(&tempFilePath);
delete formatTarget;
output->release();
}
int main()
{
try{
XMLPlatformUtils::Initialize();
}catch(const XMLException& e){
char* message = XMLString::transcode(e.getMessage());
fprintf(stderr, "Error during initialization! : %s\n", message);
XMLString::release(&message);
return -1;
}
char *names[]={"param1", "param2", "param3"};
char *values[]={"11", "32", "5"};
DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(XMLString::transcode("Core"));
DOMDocument* doc = impl->createDocument(0,XMLString::transcode("ParameterSettings"),0);
DOMElement* rootElem = doc->getDocumentElement();
//** create child elements
for(int i=0; i<3; i++){
DOMElement *elem = doc->createElement(XMLString::transcode("param"));
elem->setAttribute(XMLString::transcode("name"), XMLString::transcode(names[i]));
elem->setAttribute(XMLString::transcode("value"),XMLString::transcode(values[i]));
rootElem->appendChild(elem);
}
OutputXML(doc, "sample.xml");
doc->release();
XMLPlatformUtils::Terminate();
return 0;
}
Output XML file
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<ParameterSettings>
<param name="param1" value="11"/>
<param name="param2" value="32"/>
<param name="param3" value="5"/>
</ParameterSettings>