本文整理汇总了C++中DOMDocument::getElementsByTagName方法的典型用法代码示例。如果您正苦于以下问题:C++ DOMDocument::getElementsByTagName方法的具体用法?C++ DOMDocument::getElementsByTagName怎么用?C++ DOMDocument::getElementsByTagName使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DOMDocument
的用法示例。
在下文中一共展示了DOMDocument::getElementsByTagName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: parseDOM
/**
* Private method to orchestrate the XML parsing using DOM.
*/
int ParameterSet::parseDOM(const char* xmlFile)
{
bool doNamespaces = true;
bool doSchema = true;
bool schemaFullChecking = true;
// Instantiate the DOM parser.
static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull };
DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(gLS);
DOMBuilder *parser = ((DOMImplementationLS*)impl)->createDOMBuilder(DOMImplementationLS::MODE_SYNCHRONOUS, 0);
parser->setFeature(XMLUni::fgDOMNamespaces, doNamespaces);
parser->setFeature(XMLUni::fgXercesSchema, doSchema);
parser->setFeature(XMLUni::fgXercesSchemaFullChecking, schemaFullChecking);
parser->setFeature(XMLUni::fgDOMValidation, true);
// enable datatype normalization - default is off
parser->setFeature(XMLUni::fgDOMDatatypeNormalization, true);
/*******************
// optionally you can implement your DOMErrorHandler (e.g. MyDOMErrorHandler)
// and set it to the builder
*******************/
MyDOMErrorHandler* errHandler = new MyDOMErrorHandler();
parser->setErrorHandler(errHandler);
DOMDocument *doc = 0;
try {
doc = parser->parseURI(xmlFile);
std::cout << "parsed file: " << xmlFile <<"\n";
// Get all parameters
DOMNodeList * paramNodes = doc->getElementsByTagName(PARAMETER_TAG_NAME);
if(NULL != paramNodes) {
processParamNodes(paramNodes);
}
}
catch (const XMLException& toCatch) {
char* message = XMLString::transcode(toCatch.getMessage());
std::cout << "Exception message is: \n" << message << "\n";
XMLString::release(&message);
return -1;
}
catch (const DOMException& toCatch) {
char* message = XMLString::transcode(toCatch.msg);
std::cout << "Exception message is: \n" << message << "\n";
XMLString::release(&message);
return -1;
}
catch (...) {
std::cout << "Unexpected Exception in ParameterSet\n" ;
return -1;
}
parser->release();
delete errHandler;
return 0;
}
示例2: ParseXmlFromTMS
// 解析TMS返回xml
bool CTMSSensor::ParseXmlFromTMS(std::string &retXml,int &nRet)
{
XercesDOMParser *ptrParser = new XercesDOMParser;
ptrParser->setValidationScheme( XercesDOMParser::Val_Never );
ptrParser->setDoNamespaces( true );
ptrParser->setDoSchema( false );
ptrParser->setLoadExternalDTD( false );
InputSource* ptrInputsource = new MemBufInputSource((XMLByte*)retXml.c_str(), retXml.size(), "bufId");
try
{
ptrParser->parse(*ptrInputsource);
DOMDocument* ptrDoc = ptrParser->getDocument();
// 读取ret节点
DOMNodeList *ptrNodeList = ptrDoc->getElementsByTagName(C2X("ret"));
if(ptrNodeList == NULL)
{
LOGIDFMT(ULOG_ERROR,ERROR_PARSE_MONITORSTATE_XML,"ParseXmlFromTMS:ret");
return false;
}
else
{
if(ptrNodeList->getLength() == 0)
{
LOGIDFMT(ULOG_ERROR,ERROR_PARSE_MONITORSTATE_XML,"ParseXmlFromTMS:ret");
return false;
}
DOMNode* ptrNode = ptrNodeList->item(0);
char* pstate = XMLString::transcode(ptrNode->getFirstChild()->getNodeValue());
std::string str_state = pstate;
if(!str_state.empty())
{
nRet = atoi(str_state.c_str());
}
XMLString::release(&pstate);
//LOGINFFMT("%s,%s\n",str_name.c_str(),str_state.c_str());
}
}
catch( XMLException& e )
{
char* message = XMLString::transcode( e.getMessage() );
XMLString::release( &message );
LOGIDFMT(ULOG_ERROR,ERROR_PARSE_MONITORSTATE_XML,message);
delete ptrParser;
ptrInputsource = NULL;
delete ptrInputsource;
ptrParser = NULL;
}
delete ptrParser;
delete ptrInputsource;
ptrInputsource = NULL;
ptrParser = NULL;
return true;
}
示例3: validateXMLs
bool validateXMLs(char* xmlDirPath, XercesDOMParser* parser)
{
DIR *pDIR;
struct dirent *entry;
cout<<endl<<"Starting validateXMLs... "<<endl;
if( pDIR = opendir(xmlDirPath) )
{
while( entry = readdir(pDIR) )
{
if( strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0 )
{
static int index = 0;
if ( entry->d_type == DT_DIR )
{
continue;
}
string fullPath = string(xmlDirPath) + entry->d_name;
if ( fullPath.find(".xml")==string::npos )
{
continue;
}
parser->parse(fullPath.c_str());
if ( verboseOutput )
{
DOMDocument* doc = parser->getDocument();
DOMNodeList *lst = doc->getElementsByTagName(XS("epp"));
browseTree(lst->item(0));
}
int rc = parser->getErrorCount();
if ( rc == 0 )
{
cout<<"PASSED:: FILE: "<<fullPath;
}
else
{
cout<<"FAILED:: FILE: "<<fullPath;
}
cout<<endl;
}
}
closedir(pDIR);
}
cout<<endl<<"Starting validateXMLs...done "<<endl;
return true;
}
示例4: serializeMoFileToXML
int ModelicaXML::serializeMoFileToXML(char* fileName)
{
// ModelicaXML filename (normal operation)
DOMElement *pModelicaXMLElement = createModelicaXMLDOMElement(fileName);
if (pModelicaXMLElement) pRootElementModelica->appendChild(pModelicaXMLElement);
// vomit the current XML Document to file
std::string xmlFile(fileName);
xmlFile += ".xml";
serializeXMLDocumentToFile(xmlFile);
XMLSize_t elementCount = pModelicaXMLDoc->getElementsByTagName(X("*"))->getLength();
std::cout << std::endl;
std::cout << "The tree serialized contains: " << elementCount << " elements." << std::endl;
return 0;
}
示例5: getSubAlgorithm
bool ConfigurationFileHandler::getSubAlgorithm(std::string algorithm, std::string subalgorithm, std::string* result){
#ifdef BRICS_XERCES_ENABLE
if (errorsOccured) {
return false;
}
DOMNode* current = NULL;
DOMNode* attributeNode = NULL;
XMLCh* algorithmName = XMLString::transcode(algorithm.c_str());
XMLCh* subAlgorithmName = XMLString::transcode(subalgorithm.c_str());
XMLCh* implementationString = XMLString::transcode("implementation");
bool subAlgorithmFound = false;
DOMDocument* doc = parser->getDocument();
DOMNodeList* root = doc->getElementsByTagName(algorithmName);
if (root->getLength() > 1) {
LOG(WARNING) << "More than one " << algorithm << " found, taking the first one";
} else if(root->getLength() < 1) {
LOG(WARNING) << "No algorithm called " << algorithm << " found.";
return false; //TODO release resouces
}
current = root->item(0);
//search in children notes
for (current = current->getFirstChild()->getNextSibling(); current!=NULL; current = current->getNextSibling()) {
string nodeName = XMLString::transcode(current->getNodeName());
if (nodeName.compare(subalgorithm) == 0) {
DOMNamedNodeMap* attributesList = current->getAttributes();
attributeNode = attributesList->getNamedItem(implementationString);
if (attributeNode != 0) {
*result = XMLString::transcode(attributeNode->getNodeValue());
subAlgorithmFound = true;
break; //take only first found
}
}
}
XMLString::release(&algorithmName);
XMLString::release(&subAlgorithmName);
XMLString::release(&implementationString);
return subAlgorithmFound;
#else
return false;
#endif
}
示例6: MemBuf
/*
\brief It accepts a XML (ascii) buffer and it parses it.
This function is used when we have a char buffer containing an XML fragment, and we have to parse it.
This function returns the list of PSML items (<section>) contained in the XML buffer.
\param Buffer: pointer to a buffer that contains the XML fragment (in ascii).
\param BufSize: number of valid bytes in the previous buffer; not NULL terminated buffers are supported as well.
\return A pointer to the list of <section> nodes contained into the XML fragment if everything
is fine, NULL otherwise.
In case of error, the error message can be retrieved by the GetLastError() method.
*/
DOMNodeList *CPSMLReader::ParseMemBuf(char *Buffer, int BytesToParse)
{
DOMDocument *Document;
XMLCh TempBuffer[NETPDL_MAX_STRING + 1];
MemBufInputSource MemBuf( (const XMLByte *) Buffer, BytesToParse, "", false);
try
{
// Reset any other document previously created
m_DOMParser->resetDocumentPool();
// Load the description in memory and get document root
m_DOMParser->parse(MemBuf);
Document= m_DOMParser->getDocument();
if ( (Document->getDocumentElement()) == NULL)
{
errorsnprintf(__FILE__, __FUNCTION__, __LINE__, m_errbuf, sizeof(m_errbuf),
"Fatal error: cannot parse PSML file. Possible errors: "
"wrong file location, or not well-formed XML file.");
return NULL;
}
}
catch (...)
{
errorsnprintf(__FILE__, __FUNCTION__, __LINE__, m_errbuf, sizeof(m_errbuf), "Unexpected exception during PSML buffer parsing.");
return NULL;
}
if (Document == NULL)
{
errorsnprintf(__FILE__, __FUNCTION__, __LINE__, m_errbuf, sizeof(m_errbuf), "Unexpected exception during PSML buffer parsing.");
return NULL;
}
XMLString::transcode(PSML_SECTION, TempBuffer, NETPDL_MAX_STRING);
// After parsing the '<packet>' fragment, let's list the <section> contained into it
return Document->getElementsByTagName(TempBuffer);
}
示例7: getAttribute
bool ConfigurationFileHandler::getAttribute(std::string algorithm, std::string attribute, int* result) {
#ifdef BRICS_XERCES_ENABLE
if (errorsOccured) {
return false;
}
DOMNode* current = NULL;
DOMNode* attributeNode = NULL;
XMLCh* algorithmName = XMLString::transcode(algorithm.c_str());
XMLCh* attributeName = XMLString::transcode(attribute.c_str());
string tmpResult;
bool attributeFound = false;
DOMDocument* doc = parser->getDocument();
DOMNodeList* root = doc->getElementsByTagName(algorithmName);
if (root->getLength() > 1) {
LOG(WARNING) << "More than one " << algorithm << " found, taking the first one";
} else if(root->getLength() < 1) {
LOG(WARNING) << "No algorithm called " << algorithm << " found.";
return false; //TODO release resouces
}
current = root->item(0);
DOMNamedNodeMap* attributesList = current->getAttributes();
attributeNode = attributesList->getNamedItem(attributeName);
if (attributeNode != 0) {
tmpResult = XMLString::transcode(attributeNode->getNodeValue());
*result = atoi(tmpResult.c_str());
attributeFound = true;
}
XMLString::release(&algorithmName);
XMLString::release(&attributeName);
return attributeFound;
#else
return false;
#endif
}
示例8: XS
PerfPart::PerfPart( PMLDocument *doc, ScorePart *part ){
m_doc = doc;
DOMDocument *domdoc = part->getElement()->getOwnerDocument();
m_scorePart = part;
m_element = domdoc->createElement( XS("perfpart") ); //'perfpart' tag is the m_element for this class
//create part attribute
m_element->setAttribute( XS("part"), XS( m_scorePart->getID().c_str() ) );
//append part to performance element
DOMElement *perf = (DOMElement*)domdoc->getElementsByTagName(XS("performance"))->item(0);
perf->appendChild( m_element );
DOMNodeList *nl = m_element->getElementsByTagName(XS(PNote::Tag));
for( int i=0; i<nl->getLength(); i++ ){
m_notes.push_back( new PNote( m_doc, (DOMElement*)nl->item(i) ) );
}
}
示例9: main
int main(int argc, char ** argv) {
//
// Initialize the Xerces-c environment
//
try
{
XMLPlatformUtils::Initialize();
}
catch (const XMLException& toCatch)
{
fprintf(stderr, "Error during initialization of xerces-c: %s\n",
XMLString::transcode(toCatch.getMessage()));
return 1;
}
//
// Parse the command line, which should specify exactly one file, which is an
// xml file containing the list of test files to be processed.
//
if (argc != 2) {
printf("usage: %s file_name \n"
" where file name is the xml file specifying the list of test files.", argv[0]);
return 1;
}
DOMDocument* fileListDoc = parseFile(argv[1]);
if (fileListDoc == 0) return 1;
//
// Iterate over the list of files, running each as a test.
//
XMLCh tempStr[4000];
XMLString::transcode("testFile", tempStr, 3999);
DOMNodeList* list = fileListDoc->getElementsByTagName(tempStr);
int i;
int numFiles = list->getLength();
for (i=0; i<numFiles; i++)
{
++gTestsRun;
DOMNode* tmpNode3 = list->item(i);
XMLString::transcode("name", tempStr, 3999);
const XMLCh* fileName = ((DOMElement*) tmpNode3)->getAttribute(tempStr);
if (processTestFile(fileName) == false)
++gTestsFailed;
};
//
// We are done. Print out a summary of the results
//
printf("Encoding Tests Results Summary: \n"
" %d encoding tests run.\n"
" %d tests passed,\n"
" %d tests failed\n", gTestsRun, gTestsRun-gTestsFailed, gTestsFailed);
delete parser;
parser = 0;
return 0;
};
示例10: processTestFile
//------------------------------------------------------------------------
//
// processTestFile Given the file name of an encoding test xml file,
// run it.
//
//------------------------------------------------------------------------
static bool processTestFile(const XMLCh* fileName)
{
//
// Send the input file through the parse, create a DOM document for it.
//
char cFileName[4000];
XMLString::transcode(fileName, cFileName, 3999);
DOMDocument* testDoc = parseFile(cFileName);
if (testDoc == 0)
return false; // parse errors in the source xml.
//
// Pull the "data" element out of the document.
//
XMLCh tempStr[4000];
XMLString::transcode("data", tempStr, 3999);
DOMNodeList* nl = testDoc->getElementsByTagName(tempStr);
if (nl->getLength() != 1) {
fprintf(stderr, "Test file \"%s\" must have exactly one \"data\" element.\n", cFileName);
return false;
};
DOMNode* tmpNode = nl->item(0);
DOMElement* data = (DOMElement*) tmpNode;
//
// Build up a string containing the character data contents of the data element.
//
DOMNode* child;
XMLBuffer elData;
for (child=data->getFirstChild(); child != 0; child= child->getNextSibling())
{
if (child->getNodeType() == DOMNode::COMMENT_NODE)
continue;
if (! (child->getNodeType() == DOMNode::TEXT_NODE ||
child->getNodeType() == DOMNode::CDATA_SECTION_NODE ||
child->getNodeType() == DOMNode::ENTITY_REFERENCE_NODE))
{
fprintf(stderr, "Test file \"%s\": data element contains unexpected children.",
cFileName);
return false;
}
elData.append(((DOMCharacterData *)child)->getData());
};
//
// Pull the "udata" element out of the document
//
XMLString::transcode("udata", tempStr, 3999);
nl = testDoc->getElementsByTagName(tempStr);
if (nl->getLength() != 1) {
fprintf(stderr, "Test file \"%s\" must have exactly one \"udata\" element.\n", cFileName);
return false;
};
DOMNode* tmpNode1 = nl->item(0);
DOMElement* udata = (DOMElement*) tmpNode1;
//
// Build up a string containing the character data contents of the udata element.
// This will consist of a whole bunch hex numbers, still in string from
//
XMLBuffer rawUData;
for (child=udata->getFirstChild(); child != 0; child= child->getNextSibling())
{
if (child->getNodeType() == DOMNode::COMMENT_NODE)
continue;
if (! (child->getNodeType() == DOMNode::TEXT_NODE ||
child->getNodeType() == DOMNode::CDATA_SECTION_NODE ||
child->getNodeType() == DOMNode::ENTITY_REFERENCE_NODE))
{
fprintf(stderr, "Test file \"%s\": udata element contains unexpected children.",
cFileName);
return false;
}
rawUData.append(((DOMCharacterData *)child)->getData());
};
//
// Convert the raw (hex numbers) form of the udata to the corresponding string.
//
XMLBuffer uData;
unsigned int rawIndex = 0;
while (rawIndex < rawUData.getLen())
{
eatWhiteSpace(rawUData.getRawBuffer(), rawIndex);
XMLCh c = convertHexValue(rawUData.getRawBuffer(), rawIndex);
if (c > 0)
uData.append(c);
else
if (rawIndex < rawUData.getLen())
{
//.........这里部分代码省略.........
示例11: main
/*
* main function
*/
int main(int argc, char** argv) {
//Scene root, to load all things
osg::ref_ptr<osg::Group> root = new osg::Group;
//To add urban background into the scene
osg::ref_ptr<osg::Node> city = osgDB::readNodeFile("Data/cityLOD0A.osg");
// osg::ref_ptr<osg::Node> city = osgDB::readNodeFile("Data/cityLOD1.osg");
osg::ref_ptr<osg::Node> others = osgDB::readNodeFile("Data/others.osg");
// optimize the scene graph, remove redundant nodes and state etc.
osgUtil::Optimizer optimizer;
optimizer.optimize(city);
root->addChild(city);
root->addChild(others);
//A camera for HUD text
osg::ref_ptr<osg::Camera> Cam = new osg::Camera;
//Get screen center to be stored in two global variants to be used in later calculation
GetScreenCenter(ScrCenterX, ScrCenterY);
SetUpCamera(Cam);
root->addChild(Cam);
//Here needs this geode to be replaced in the loop, otherwise impossible to add texts into scene
std::string datapath, positionpath;
//A simple function to differentiate displayed info for each function
MatchDataPosition(datapath, positionpath);
datapath = "Data/RoadNamesFrench.xml";
positionpath = "Data/Position1.xml";
myXparser datasetParser;
myXparser positionParser;
datasetParser.readXMLFile(datapath);
positionParser.readXMLFile(positionpath);
DOMDocument* datasetDoc = datasetParser.getParseredDoc();
DOMDocument* positionDoc = positionParser.getParseredDoc();
DOMNodeList* dataset = datasetDoc->getElementsByTagName(
XMLString::transcode("Info"));
DOMNodeList* position = positionDoc->getElementsByTagName(
XMLString::transcode("Info"));
// osg::ref_ptr<osg::Geode> textnode = loadInfo(dataset, position);
// osg::ref_ptr<osg::Group> textGroup = new osg::Group;
// textGroup->addChild(textnode);
osg::ref_ptr<osg::Group> textGroup = loadInfo(dataset, position);
root->addChild(textGroup);
//Pour afficher des cercles sous les textes pour repérer la position sur la carte
osg::ref_ptr<osg::Shape> myCircle (new osg::Cylinder(osg::Vec3d(0.0, 0.0, 0.0), 10.0f, 0.0f));
osg::ref_ptr<osg::ShapeDrawable> circleDrawable (new osg::ShapeDrawable(myCircle.get()));
circleDrawable->setColor(osg::Vec4d(0.0,0.0,0.0,1.0));
osg::ref_ptr<osg::Group> circleGroup (new osg::Group);
osg::ref_ptr<osg::Geode> circleGeode (new osg::Geode);
const XMLCh* xmlch_x;
const XMLCh* xmlch_y;
const XMLCh* xmlch_z;
root->addChild(circleGroup.get());
for(int i=0; i < (position->getLength()); i++){
osg::Vec3d positionTexte;
DOMNode* positionNode = position->item(i);
DOMElement* positionElement = dynamic_cast<xercesc::DOMElement*>(positionNode);
xmlch_x = positionElement->getAttribute(XMLString::transcode("X"));
xmlch_y = positionElement->getAttribute(XMLString::transcode("Y"));
xmlch_z = positionElement->getAttribute(XMLString::transcode("Z"));
osg::Vec3 ObjTextPos;
ObjTextPos.set(atoi(XMLString::transcode(xmlch_x)),
atoi(XMLString::transcode(xmlch_y)),
atoi(XMLString::transcode(xmlch_z)));
osg::ref_ptr<osg::PositionAttitudeTransform> positionCourant (new osg::PositionAttitudeTransform);
positionCourant->setPosition(ObjTextPos);
circleGeode->addChild(new osg::Geode);
osg::Geode* noeudCourant = circleGeode->getChild(i)->asGeode();
noeudCourant->addDrawable(circleDrawable.get());
circleGroup->addChild(positionCourant);
positionCourant->addChild(noeudCourant);
}
//.........这里部分代码省略.........
示例12: osmloader_step
//.........这里部分代码省略.........
DOMNode* current = 0;
DOMNode* currentChild = 0;
DOMNode* attributeNode = 0;
DOMNamedNodeMap* attributesList = 0;
DOMNamedNodeMap* childAttributesList = 0;
XMLCh* rootName = XMLString::transcode("osm");
XMLCh* nodeName = XMLString::transcode("node");
XMLCh* tagName = XMLString::transcode("tag");
XMLCh* kName = XMLString::transcode("k");
XMLCh* vName = XMLString::transcode("v");
XMLCh* idName = XMLString::transcode("id");
XMLCh* latName = XMLString::transcode("lat");
XMLCh* lonName = XMLString::transcode("lon");
XMLCh* wayName = XMLString::transcode("way");
XMLCh* refName = XMLString::transcode("ref");
XMLCh* versionName = XMLString::transcode("version");
string tmpResult;
string osmAttributePrefix = "osm:";
unsigned int nodeCounter = 0;
unsigned int wayCounter = 0;
/* <osm version="0.6" generator="Overpass API">
* <note>The data included in this document is from www.openstreetmap.org. The data is made available under ODbL.</note>
* <meta osm_base="2015-01-07T12:43:02Z"/>
* <node id="21101298" lat="50.7776577" lon="7.1853241"><tag k="crossing" v="traffic_signals"/>
* <tag k="highway" v="traffic_signals"/>
* </node>
* </osm>
*/
DOMDocument* doc = parser->getDocument();
/* root node */
DOMNodeList* root = doc->getElementsByTagName(rootName);
if (root->getLength() > 1) {
LOG(WARNING) << "More than one osm elemnt found, taking the first one";
} else if(root->getLength() < 1) {
LOG(ERROR) << "No osm elemnt found.";
return ;
}
current = root->item(0);
attributesList = current->getAttributes();
attributeNode = attributesList->getNamedItem(versionName);
if (attributeNode != 0) {
tmpResult = XMLString::transcode(attributeNode->getNodeValue());
LOG(INFO) << "osm version = " << tmpResult;
}
/* osm nodes */
DOMNodeList* osmNodes = doc->getElementsByTagName(nodeName);
double x = -1.0;
double y = -1.0;
double z = 0.0;
for (int i = 0; i < osmNodes->getLength(); ++i) {
unsigned int id = 0;
double lon = -1.0;
double lat = -1.0;
vector<brics_3d::rsg::Attribute> tags;
brics_3d::rsg::TimeStamp time = wmHandle->now();
current = osmNodes->item(i);
示例13: main
int main(int argC, char*[])
{
// Initialize the XML4C2 system.
try
{
XMLPlatformUtils::Initialize();
}
catch(const XMLException& toCatch)
{
char *pMsg = XMLString::transcode(toCatch.getMessage());
XERCES_STD_QUALIFIER cerr << "Error during Xerces-c Initialization.\n"
<< " Exception message:"
<< pMsg;
XMLString::release(&pMsg);
return 1;
}
// Watch for special case help request
int errorCode = 0;
if (argC > 1)
{
XERCES_STD_QUALIFIER cout << "\nUsage:\n"
" CreateDOMDocument\n\n"
"This program creates a new DOM document from scratch in memory.\n"
"It then prints the count of elements in the tree.\n"
<< XERCES_STD_QUALIFIER endl;
errorCode = 1;
}
if(errorCode) {
XMLPlatformUtils::Terminate();
return errorCode;
}
{
// Nest entire test in an inner block.
// The tree we create below is the same that the XercesDOMParser would
// have created, except that no whitespace text nodes would be created.
// <company>
// <product>Xerces-C</product>
// <category idea='great'>XML Parsing Tools</category>
// <developedBy>Apache Software Foundation</developedBy>
// </company>
DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(X("Core"));
if (impl != NULL)
{
try
{
DOMDocument* doc = impl->createDocument(
0, // root element namespace URI.
X("company"), // root element name
0); // document type object (DTD).
DOMElement* rootElem = doc->getDocumentElement();
DOMElement* prodElem = doc->createElement(X("product"));
rootElem->appendChild(prodElem);
DOMText* prodDataVal = doc->createTextNode(X("Xerces-C"));
prodElem->appendChild(prodDataVal);
DOMElement* catElem = doc->createElement(X("category"));
rootElem->appendChild(catElem);
catElem->setAttribute(X("idea"), X("great"));
DOMText* catDataVal = doc->createTextNode(X("XML Parsing Tools"));
catElem->appendChild(catDataVal);
DOMElement* devByElem = doc->createElement(X("developedBy"));
rootElem->appendChild(devByElem);
DOMText* devByDataVal = doc->createTextNode(X("Apache Software Foundation"));
devByElem->appendChild(devByDataVal);
//
// Now count the number of elements in the above DOM tree.
//
const XMLSize_t elementCount = doc->getElementsByTagName(X("*"))->getLength();
XERCES_STD_QUALIFIER cout << "The tree just created contains: " << elementCount
<< " elements." << XERCES_STD_QUALIFIER endl;
doc->release();
}
catch (const OutOfMemoryException&)
{
XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl;
errorCode = 5;
}
catch (const DOMException& e)
{
XERCES_STD_QUALIFIER cerr << "DOMException code is: " << e.code << XERCES_STD_QUALIFIER endl;
errorCode = 2;
}
catch (...)
{
//.........这里部分代码省略.........
示例14: main
//.........这里部分代码省略.........
DOMElement* rivalsElem = doc->createElement(X("rivals"));
rootElem->appendChild(rivalsElem);
DOMText* rivalsDataVal = doc->createTextNode(X("Warrriors"));
rivalsElem->appendChild(rivalsDataVal);
DOMElement* policeElem = doc->createElement(X("police"));
rootElem->appendChild(policeElem);
DOMText* policeDataVal = doc->createTextNode(X("popo"));
policeElem->appendChild(policeDataVal);
DOMElement* drugsElem = doc->createElement(X("drugs"));
rootElem->appendChild(drugsElem);
DOMText* drugsDataVal = doc->createTextNode(X("codiene"));
drugsElem->appendChild(drugsDataVal);
// create drugs elem children
DOMElement* mixElem = doc->createElement(X("mix"));
DOMElement* spriteElem = doc->createElement(X("sprite"));
DOMElement* leanElem = doc->createElement(X("lean"));
// append drugs elem children
drugsElem->appendChild(mixElem);
drugsElem->appendChild(spriteElem);
drugsElem->appendChild(leanElem);
DOMElement* crimeElem = doc->createElement(X("crime"));
rootElem->appendChild(crimeElem);
DOMText* crimeDataVal = doc->createTextNode(X("187"));
crimeElem->appendChild(crimeDataVal);
//
// Now count the number of elements in the above DOM tree.
//
const XMLSize_t elementCount = doc->getElementsByTagName(X("*"))->getLength();
XERCES_STD_QUALIFIER cout << "The tree just created contains: " << elementCount
<< " elements." << XERCES_STD_QUALIFIER endl;
// create serializer instance
DOMLSSerializer *theSerializer = ((DOMImplementationLS*) impl)->createLSSerializer();
// create output instance
DOMLSOutput *theOutputDesc = ((DOMImplementationLS*) impl)->createLSOutput();
// referenced the following http://stackoverflow.com/questions/2897317/writing-xml-with-xerces-3-0-1-and-c-on-windows
// set output from serializer to stdout
XMLFormatTarget *myFormTarget;
myFormTarget = new StdOutFormatTarget();
theOutputDesc->setByteStream(myFormTarget);
// Make the output more human readable by inserting line feeds.
if (theSerializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
theSerializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true);
// The end-of-line sequence of characters to be used in the XML being written out.
theSerializer->setNewLine(XMLString::transcode("\r\n"));
// output the DOM
theSerializer->write(doc, theOutputDesc);
cout << endl << endl << "*****************************************" << endl;
// Using DOMTreeWalker class to traverse tree
// create tree walker
DOMTreeWalker* walker = doc->createTreeWalker(rootElem,
DOMNodeFilter::SHOW_ELEMENT,
NULL,
true);
示例15: clsDataClientConfig
list<ClsDataClientConfig> ClsDataClientConfigReader::getDataClientConfig(string strFileName) {
#ifdef DEBUG_CLSDATACLIENTCONFIGREADER
cout << "ClsDataClientConfigReader::getDataClientConfig()" << endl;
#endif
list<ClsDataClientConfig> lstConfigs;
#ifdef DEBUG_CLSDATACLIENTCONFIGREADER
cout << "reading settings from: " << strFileName << endl;
#endif
bool errorsOccured = false;
static bool gDoNamespaces = false;
if(!bXMLPlatformInitialized){
try {
XMLPlatformUtils::Initialize();
}
catch(const XMLException& toCatch) {
cerr << "Error during Xerces-c Initialization.\n"
<< " Exception message:"
<< toCatch.getMessage() << endl;
bXMLPlatformInitialized = false;
errorsOccured = true;
// return;
}
bXMLPlatformInitialized = true;
errorsOccured = false;
}
//--------------------
if (!errorsOccured) {
XercesDOMParser* parser = new XercesDOMParser();
parser->setValidationScheme(XercesDOMParser::Val_Never);
/*
XercesDOMParser::Val_Never;
XercesDOMParser::Val_Auto;
XercesDOMParser::Val_Always;
*/
parser->setDoNamespaces(gDoNamespaces);
ErrorHandler* errHandler = (ErrorHandler*) new HandlerBase();
parser->setErrorHandler(errHandler);
try {
parser->parse(strFileName.c_str());
int errorCount = parser->getErrorCount();
if (errorCount > 0){
errorsOccured = true;
}
} catch (const XMLException& e) {
cerr << "An error occured during parsing (XMLException)\n NMessage: " << XMLString::transcode(e.getMessage()) << endl;
ClsDataClientConfigReaderException clsDataClientConfigReaderException(XMLString::transcode(e.getMessage()));
errorsOccured = true;
throw clsDataClientConfigReaderException;
} catch (const DOMException& e) {
cerr << "An error occured during parsing (DOMException)\n DMessage: " << XMLString::transcode(e.msg) << endl;
ClsDataClientConfigReaderException clsDataClientConfigReaderException(XMLString::transcode(e.msg));
errorsOccured = true;
throw clsDataClientConfigReaderException;
} catch (const SAXException& e) {
cerr << "An error occured during parsing (SAXException)\n DMessage: " << XMLString::transcode(e.getMessage()) << endl;
ClsDataClientConfigReaderException clsDataClientConfigReaderException(XMLString::transcode(e.getMessage()));
errorsOccured = true;
throw clsDataClientConfigReaderException;
} catch (...) {
cerr << "An error occured during parsing\n " << endl;
errorsOccured = true;
ClsDataClientConfigReaderException clsDataClientConfigReaderException(ClsDataClientConfigReaderException::PARSE_ERROR);
throw clsDataClientConfigReaderException;
}
/* DOMNode* dnIqrConfig; */
DOMDocument *ddocConfig = parser->getDocument();
DOMNodeList* dnlstClients = ddocConfig->getElementsByTagName(XMLString::transcode(ConfigTagLibrary::DataClientTag()));
try{
if(dnlstClients->getLength()>0){
DOMNode* dnValue = NULL;
unsigned int ii = 0;
while( ii< dnlstClients->getLength()){
DOMNode* dnClient = dnlstClients->item(ii);
ii++;
string strType = getAttributeValue(dnClient, ConfigTagLibrary::TypeTag(), true);
string strID = getAttributeValue(dnClient, ConfigTagLibrary::IDTag(), false);
ClsDataClientConfig clsDataClientConfig(strID, strType);
DOMNodeList* dnlstClientChildren = dnClient->getChildNodes();
unsigned int i2 = 0;
while( i2< dnlstClientChildren->getLength()){
DOMNode* dnClientChild = dnlstClientChildren->item(i2);
if(dnClientChild->getNodeType() == 1){
string strName = XMLString::transcode(dnClientChild->getNodeName());
//.........这里部分代码省略.........