DOMElement * DSIGObject::createBlankObject(void) { safeBuffer str; const XMLCh * prefix; DOMDocument *doc = mp_env->getParentDocument(); prefix = mp_env->getDSIGNSPrefix(); // Create the transform node makeQName(str, prefix, s_Object); mp_objectNode = doc->createElementNS(DSIGConstants::s_unicodeStrURIDSIG, str.rawXMLChBuffer()); mp_idAttr = NULL; mp_mimeTypeAttr = NULL; mp_encodingAttr = NULL; return (DOMElement *) mp_objectNode; }
DOMElement * DSIGTransformEnvelope::createBlankTransform(DOMDocument * parentDoc) { safeBuffer str; const XMLCh * prefix; DOMElement *ret; DOMDocument *doc = mp_env->getParentDocument(); prefix = mp_env->getDSIGNSPrefix(); // Create the transform node makeQName(str, prefix, "Transform"); ret = doc->createElementNS(DSIGConstants::s_unicodeStrURIDSIG, str.rawXMLChBuffer()); ret->setAttributeNS(NULL,DSIGConstants::s_unicodeStrAlgorithm, DSIGConstants::s_unicodeStrURIENVELOPE); mp_txfmNode = ret; return ret; }
DOMElement * XKMSAuthenticationImpl::createBlankAuthentication(const XMLCh * id) { // Get some setup values safeBuffer str; DOMDocument *doc = mp_env->getParentDocument(); const XMLCh * prefix = mp_env->getXKMSNSPrefix(); makeQName(str, prefix, XKMSConstants::s_tagAuthentication); mp_authenticationElement = doc->createElementNS(XKMSConstants::s_unicodeStrURIXKMS, str.rawXMLChBuffer()); mp_env->doPrettyPrint(mp_authenticationElement); // This isn't used immediately - it is simply held for when we create a signature mp_keyBindingId = id; return mp_authenticationElement; }
/* \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); }
DSIGSignature * XKMSAuthenticationImpl::addKeyBindingAuthenticationSignature( canonicalizationMethod cm, signatureMethod sm, hashMethod hm) { if (mp_keyBindingId == NULL) { throw XSECException(XSECException::XKMSError, "XKMSAuthenticationImpl::addKeyBindingAuthenticationSignature - called prior to key infos being added"); } DSIGSignature * ret = m_prov.newSignature(); DOMElement * elt = ret->createBlankSignature(mp_env->getParentDocument(), cm, sm, hm); /* Create the enveloping reference */ safeBuffer sb; sb.sbXMLChIn(DSIGConstants::s_unicodeStrEmpty); sb.sbXMLChAppendCh(chPound); sb.sbXMLChCat(mp_keyBindingId); DSIGReference *ref = ret->createReference(sb.rawXMLChBuffer()); ref->appendCanonicalizationTransform(CANON_C14NE_COM); /* Embed the signature in the document inside a KeyBindingAuthentication element */ safeBuffer str; DOMDocument *doc = mp_env->getParentDocument(); const XMLCh * prefix = mp_env->getXKMSNSPrefix(); makeQName(str, prefix, XKMSConstants::s_tagKeyBindingAuthentication); DOMElement * t = doc->createElementNS(XKMSConstants::s_unicodeStrURIXKMS, str.rawXMLChBuffer()); mp_env->doPrettyPrint(t); t->appendChild(elt); mp_env->doPrettyPrint(t); mp_authenticationElement->appendChild(t); mp_env->doPrettyPrint(mp_authenticationElement); return ret; }
IDOMDocument* DOMDocument::createInstance(WebCore::Document* d) { if (!d) return 0; HRESULT hr; IDOMDocument* domDocument = 0; if (d->isHTMLDocument()) { DOMHTMLDocument* newDocument = new DOMHTMLDocument(d); hr = newDocument->QueryInterface(IID_IDOMDocument, (void**)&domDocument); } else { DOMDocument* newDocument = new DOMDocument(d); hr = newDocument->QueryInterface(IID_IDOMDocument, (void**)&domDocument); } if (FAILED(hr)) return 0; return domDocument; }
XmlNode addChild(const char *name, const char *value) { XMLCh *tempStr = NULL; tempStr = XMLString::transcode(name); DOMElement *element = doc->createElement(tempStr); DOMNode *cnode = node->appendChild(element); if (value != NULL) { tempStr = XMLString::transcode(value); element->setTextContent(tempStr); } XMLString::release(&tempStr); return XmlNode(cnode,doc); }
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 }
// // set_element_value // void Utils:: set_element_value (xercesc::DOMElement * e, const GAME::Xml::String & element, const GAME::Xml::String & value) { using xercesc::DOMNode; using xercesc::DOMNodeList; using xercesc::DOMDocument; // There should be only 1 <name> tag in the list. GAME::Xml::String nodename; DOMNode * node = 0; DOMNodeList * list = e->getChildNodes (); size_t len = list->getLength (); for (size_t i = 0; i < len; ++ i) { // Get the name of the next node. node = list->item (i); nodename.set (node->getNodeName (), false); if (nodename == element) break; // Reset the node. node = 0; } if (node == 0) { // We need to create the <name> element. DOMDocument * doc = e->getOwnerDocument (); node = doc->createElement (element); e->appendChild (node); } // Since there are no child nodes, we can just set the // text content to the name of the object. node->setTextContent (value); }
void XENCEncryptionMethodImpl::setOAEPparams(const XMLCh * params) { if (mp_oaepParamsTextNode == NULL) { // Need to create if (mp_mgfAlgorithmAttr == NULL && mp_digestAlgorithmAttr == NULL && mp_keySizeTextNode == NULL) { mp_env->doPrettyPrint(mp_encryptionMethodElement); } // Get some setup values safeBuffer str; DOMDocument *doc = mp_env->getParentDocument(); const XMLCh * prefix = mp_env->getXENCNSPrefix(); makeQName(str, prefix, s_OAEPparams); DOMNode* inspoint = NULL; DOMElement *e = doc->createElementNS(DSIGConstants::s_unicodeStrURIXENC, str.rawXMLChBuffer()); if (mp_keySizeTextNode != NULL) { inspoint = mp_keySizeTextNode->getParentNode()->getNextSibling(); } else { inspoint = mp_encryptionMethodElement->getFirstChild(); } mp_encryptionMethodElement->insertBefore(e, inspoint); mp_env->doPrettyPrint(mp_encryptionMethodElement); e->appendChild(mp_oaepParamsTextNode = doc->createTextNode(params)); } else { mp_oaepParamsTextNode->setNodeValue(params); } }
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) ) ); } }
void SNote::align( PNote *note, bool correct ){ DOMNodeList *list = m_element->getElementsByTagName(XS("align")); DOMElement *align; if( list->getLength() == 0 ){ DOMDocument *doc = m_element->getOwnerDocument(); align = doc->createElement(XS("align")); m_element->appendChild(align); } else{ align = (DOMElement*)list->item(0); } align->setAttribute( XS("note"), XS(note->getID().c_str()) ); if( correct ) setText( align, "correct" ); else setText( align, "wrong" ); }
/** * TODO: JavaDocs * * @throws LoadException */ ConnectionTemplate *XMLConnectionTemplateLoader::loadConnectionTemplate( istream &inStream) const { DOMDocument *document; try { document = Utils::DOM::parseDocumentFromStream(inStream); document->normalizeDocument(); removeWhitespaceTextNodes(document->getDocumentElement()); } catch (const DOMParseException &ex) { throw LoadException("XMLException, see above"); } try { XMLConnectionTemplate *result = new XMLConnectionTemplate(); result->fromXML(document->getDocumentElement()); return result; } catch (const XMLReadable::XMLSerializationException &ex) { Log::error(LOG_LOCATION("XMLConnectionTemplateLoader", "loadConnectionTemplate"), "Got XMLSerializationException while creating " "template..."); throw LoadException(ex.what()); } }
/* \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 PDML items (<section>) contained in the XML buffer. \param Buffer: pointer to a buffer that contains the XML fragment (in ascii). \param BytesToParse: number of valid bytes in the previous buffer; not NULL terminated buffers are supported as well. \return A pointer to the DOM document associated to the XML fragment if everything is fine, NULL otherwise. In case of error, the error message can be retrieved by the GetLastError() method. */ DOMDocument* CPDMLReader::ParseMemBuf(char *Buffer, int BytesToParse) { DOMDocument *Document; 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 PDML 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 PDML buffer parsing."); return NULL; } if (Document == NULL) { errorsnprintf(__FILE__, __FUNCTION__, __LINE__, m_errbuf, sizeof(m_errbuf), "Unexpected exception during PDML buffer parsing."); return NULL; } return Document; }
// XSAnnotation methods void XSAnnotation::writeAnnotation(DOMNode* node, ANNOTATION_TARGET targetType) { XercesDOMParser *parser = new (fMemoryManager) XercesDOMParser(0, fMemoryManager); parser->setDoNamespaces(true); parser->setValidationScheme(XercesDOMParser::Val_Never); DOMDocument* futureOwner = (targetType == W3C_DOM_ELEMENT) ? ((DOMElement*)node)->getOwnerDocument() : (DOMDocument*)node; MemBufInputSource* memBufIS = new (fMemoryManager) MemBufInputSource ( (const XMLByte*)fContents , XMLString::stringLen(fContents)*sizeof(XMLCh) , "" , false , fMemoryManager ); memBufIS->setEncoding(XMLUni::fgXMLChEncodingString); memBufIS->setCopyBufToStream(false); try { parser->parse(*memBufIS); } catch (const XMLException&) { // REVISIT: should we really eat this? } DOMNode* newElem = futureOwner->importNode((parser->getDocument())->getDocumentElement(), true); node->insertBefore(newElem, node->getFirstChild()); delete parser; delete memBufIS; }
saml2::Assertion * gss_eap_saml_assertion_provider::parseAssertion(const gss_buffer_t buffer) { string str((char *)buffer->value, buffer->length); istringstream istream(str); DOMDocument *doc; const XMLObjectBuilder *b; try { doc = XMLToolingConfig::getConfig().getParser().parse(istream); if (doc == NULL) return NULL; b = XMLObjectBuilder::getBuilder(doc->getDocumentElement()); #ifdef __APPLE__ return (saml2::Assertion *)((void *)b->buildFromDocument(doc)); #else return dynamic_cast<saml2::Assertion *>(b->buildFromDocument(doc)); #endif } catch (exception &e) { return NULL; } }
void DSIGReference::createTransformList(void) { // Creates the transforms list safeBuffer str; const XMLCh * prefix; DOMDocument *doc = mp_env->getParentDocument(); prefix = mp_env->getDSIGNSPrefix(); if (mp_transformsNode == NULL) { // Need to create a transforms node makeQName(str, prefix, "Transforms"); mp_transformsNode = doc->createElementNS(DSIGConstants::s_unicodeStrURIDSIG, str.rawXMLChBuffer()); mp_referenceNode->insertBefore(mp_transformsNode, mp_referenceNode->getFirstChild()); if (mp_env->getPrettyPrintFlag() == true) mp_referenceNode->insertBefore(doc->createTextNode(DSIGConstants::s_unicodeStrNL), mp_transformsNode); mp_env->doPrettyPrint(mp_transformsNode); // Create the list XSECnew(mp_transformList, DSIGTransformList()); } }
std::vector<std::string> CXercesUtils::GetXpathResults(DOMElement* root, std::string querystr) { std::vector<std::string> values; DOMDocument* doc (root->getOwnerDocument ()); // Obtain namespace resolver. xsd::cxx::xml::dom::auto_ptr<DOMXPathNSResolver> resolver ( doc->createNSResolver (root)); // Create XPath expression. xsd::cxx::xml::dom::auto_ptr<DOMXPathExpression> expr ( doc->createExpression ( xsd::cxx::xml::string (querystr.c_str()).c_str (), resolver.get ())); // Execute the query. xsd::cxx::xml::dom::auto_ptr<DOMXPathResult> r ( expr->evaluate ( root, DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE /*DOMXPathResult::ITERATOR_RESULT_TYPE*/, 0)); // If no query matches, then return empty vector if (!r.get() ) return values; // Iterate over the result. for (int i=0; i < r->getSnapshotLength(); i++) { r->snapshotItem(i); DOMNode* n (r->getNodeValue ()); const XMLCh * value = n->getTextContent ( ); values.push_back(xsd::cxx::xml::transcode<char> (value)); } return values; }
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; }
// 2006/12/16 void handleFile(char* filein, char* fileout, int mode) { if (mode==_TXT2TXTMODE) { int result; if (filein == NULL) { if (fileout == NULL) result = seg->segmentStream(cin,cout); else { ofstream* fout = new ofstream(fileout); result = seg->segmentStream(cin,*fout); fout->close(); } } else { ifstream* fin = new ifstream(filein); ofstream* fout = new ofstream(fileout); result = seg->segmentStream(*fin,*fout); fin->close(); fout->close(); } // BROKEN, result is false 2006/11/07 //if (verbose) // cerr << "> Segmented in " << result << " sentences." << endl; } else if (mode==_TXT2XMLMODE) { DOMDocument* out = xmlInterface->createDocument("document"); DOMElement* root = out->getDocumentElement(); if (filein != NULL) root->setAttribute(XMLString::transcode("filename"), XMLString::transcode(filein)); DOMElement* contents = out->createElement(XMLString::transcode("content")); DOMElement* body = out->createElement(XMLString::transcode("body")); DOMElement* section = out->createElement(XMLString::transcode("section")); section->setAttribute(XMLString::transcode("analyze"), XMLString::transcode("yes")); DOMText* text = out->createTextNode(XMLString::transcode(getFileContents(filein).c_str())); section->appendChild(text); body->appendChild(section); contents->appendChild(body); root->appendChild(contents); handleDocument(out,fileout); } else if (mode==_XML2XMLMODE) { handleDocument(xmlInterface->parse(filein),fileout); } }
bool XCube::writeXML(const std::string &outputfile) { DWXML xml; xercesc::XercesDOMParser *m_DOMXmlParser1=xml.getDOMParser(); m_DOMXmlParser1->setValidationScheme( XercesDOMParser::Val_Auto ); m_DOMXmlParser1->setDoNamespaces( false ); m_DOMXmlParser1->setDoSchema( false ); m_DOMXmlParser1->setLoadExternalDTD( false ); XMLCh temp2[100]; XMLString::transcode("Core", temp2, 99); DOMImplementation* impl2 = DOMImplementationRegistry::getDOMImplementation(temp2); DOMDocument* doc = impl2->createDocument( 0, // root element namespace URI. XMLString::transcode("Schema"), // root element name 0); // document type object (DTD). if (impl2 != NULL) { try { DOMElement *cubeElem = doc->createElement(XMLString::transcode("Cube")); if(this->_name != "") cubeElem->setAttribute(XMLString::transcode("name"),XMLString::transcode(this->_name.c_str())); if(this->_fact != "") cubeElem->setAttribute(XMLString::transcode("tablename"),XMLString::transcode(this->_fact.c_str())); if(this->_dimensions.size() > 0) { for(int i = 0; i < this->_dimensions.size(); i ++) { Dimension *tempDimension = this->getDimension(this->_dimensions[i]->getName()); cubeElem->appendChild(tempDimension->recursiveXML(doc)); } } XSchema *tempschema = this->getSchema(); DOMElement* schemaElem = doc->getDocumentElement();//create root if(DataSource *tempDS = tempschema->getDataSource()) { schemaElem -> appendChild(tempDS->recursiveXML(doc)); } schemaElem -> appendChild(cubeElem); } catch (const OutOfMemoryException &) { XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl; return false; } catch (const DOMException& e) { XERCES_STD_QUALIFIER cerr << "DOMException code is: " << e.code << XERCES_STD_QUALIFIER endl; return false; } catch (...) { XERCES_STD_QUALIFIER cerr << "An error occurred creating the document" << XERCES_STD_QUALIFIER endl; return false; } } else {return false;} //use DOMwriter for export XML file //Writer Ini bool bRet = true; XMLCh tempStr[100]; XMLString::transcode("LS", tempStr, 99); DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(tempStr); DOMWriter *m_pWriter = ((DOMImplementationLS*)impl)->createDOMWriter(); //set XML File in "UTF-8" XMLCh *encoding = XMLString::transcode("UTF-8"); m_pWriter -> setEncoding(encoding); // DOMDocument* m_pDoc; const char * outfile = outputfile.c_str(); XMLFormatTarget* m_pFormatTarget = new LocalFileFormatTarget(outfile); // construct the LocalFileFormatTarget // m_pFormatTarget = new LocalFileFormatTarget(szPath); // serialize a DOMNode to the local file "myXMLFile.xml" //Write File in UTF-8 bRet = m_pWriter->writeNode(m_pFormatTarget, *doc); if (bRet == false) { return false; } else { try { // optionally, you can flush the buffer to ensure all contents are written m_pFormatTarget->flush(); delete m_pFormatTarget; delete m_DOMXmlParser1; delete m_pWriter; doc->release(); XMLPlatformUtils::Terminate(); return true; } catch (const OutOfMemoryException&) { XERCES_STD_QUALIFIER cerr << "OutOfMemoryException" << XERCES_STD_QUALIFIER endl; return false; } catch (XMLException& e) { XERCES_STD_QUALIFIER cerr << "An error occurred during creation of output transcoder. Msg is:" << XERCES_STD_QUALIFIER endl << XMLString::transcode(e.getMessage()) << XERCES_STD_QUALIFIER endl; return false; } } }
DOMDocument * XIncludeUtils::doXIncludeXMLFileDOM(const XMLCh *href, const XMLCh *relativeHref, DOMNode *includeNode, DOMDocument *parsedDocument, XMLEntityHandler* entityResolver){ if (XIncludeUtils::isInCurrentInclusionHistoryStack(href)){ /* including something back up the current history */ XIncludeUtils::reportError(parsedDocument, XMLErrs::XIncludeCircularInclusionLoop, href, href); return NULL; } if (XMLString::equals(href, parsedDocument->getBaseURI())){ /* trying to include itself */ XIncludeUtils::reportError(parsedDocument, XMLErrs::XIncludeCircularInclusionDocIncludesSelf, href, href); return NULL; } /* Instantiate the DOM parser. */ XercesDOMParser parser; parser.setDoNamespaces(true); /* don't want to recurse the xi processing here */ parser.setDoXInclude(false); /* create the schema info nodes, so that we can detect conflicting notations */ parser.setCreateSchemaInfo(true); XMLInternalErrorHandler xierrhandler; parser.setErrorHandler(&xierrhandler); DOMDocument *includedNode = NULL; try { InputSource* is=NULL; Janitor<InputSource> janIS(is); if(entityResolver) { XMLResourceIdentifier resIdentifier(XMLResourceIdentifier::ExternalEntity, relativeHref, NULL, NULL, includeNode->getBaseURI()); is=entityResolver->resolveEntity(&resIdentifier); janIS.reset(is); } if(janIS.get()!=NULL) parser.parse(*janIS.get()); else parser.parse(href); /* need to be able to release the parser but keep the document */ if (!xierrhandler.getSawError() && !xierrhandler.getSawFatal()) includedNode = parser.adoptDocument(); } catch (const XMLException& /*toCatch*/) { XIncludeUtils::reportError(parsedDocument, XMLErrs::XIncludeResourceErrorWarning, href, href); } catch (const DOMException& /*toCatch*/) { XIncludeUtils::reportError(parsedDocument, XMLErrs::XIncludeResourceErrorWarning, href, href); } catch (...) { XIncludeUtils::reportError(parsedDocument, XMLErrs::XIncludeResourceErrorWarning, href, href); } //addDocumentURIToCurrentInclusionHistoryStack(href); if(includedNode != NULL){ /* baseURI fixups - see http://www.w3.org/TR/xinclude/#base for details. */ DOMElement *topLevelElement = includedNode->getDocumentElement(); if (topLevelElement && topLevelElement->getNodeType() == DOMNode::ELEMENT_NODE ){ XMLUri parentURI(includeNode->getBaseURI()); XMLUri includedURI(includedNode->getBaseURI()); /* if the paths differ we need to add a base attribute */ if (!XMLString::equals(parentURI.getPath(), includedURI.getPath())){ if (getBaseAttrValue(topLevelElement) == NULL){ /* need to calculate the proper path difference to get the relativePath */ topLevelElement->setAttribute(fgXIBaseAttrName, relativeHref); } else { /* the included node has base of its own which takes precedence */ XIncludeLocation xil(getBaseAttrValue(topLevelElement)); if (getBaseAttrValue(includeNode) != NULL){ /* prepend any specific base modification of the xinclude node */ xil.prependPath(getBaseAttrValue(includeNode)); } topLevelElement->setAttribute(fgXIBaseAttrName, xil.getLocation()); } } } } return includedNode; }
// --------------------------------------------------------------------------- // This method assumes that currentNode is an xinclude element and parses // it accordingly, acting on what it finds. // --------------------------------------------------------------------------- bool XIncludeUtils::doDOMNodeXInclude(DOMNode *xincludeNode, DOMDocument *parsedDocument, XMLEntityHandler* entityResolver){ bool modifiedNode = false; /* the relevant attributes to look for */ const XMLCh *href = NULL; const XMLCh *parse = NULL; const XMLCh *xpointer = NULL; const XMLCh *encoding = NULL; const XMLCh *accept = NULL; const XMLCh *acceptlanguage = NULL; DOMNode *includeParent = xincludeNode->getParentNode(); if(xincludeNode->hasAttributes()) { /* get all the attributes of the node */ DOMNamedNodeMap *pAttributes = xincludeNode->getAttributes(); XMLSize_t nSize = pAttributes->getLength(); for(XMLSize_t i=0;i<nSize;++i) { DOMAttr *pAttributeNode = (DOMAttr*) pAttributes->item(i); const XMLCh *attrName = pAttributeNode->getName(); /* check each attribute against the potential useful names */ if (XMLString::equals(attrName, XIncludeUtils::fgXIIncludeHREFAttrName)){ href = pAttributeNode->getValue(); } else if (XMLString::equals(attrName, XIncludeUtils::fgXIIncludeParseAttrName)){ parse = pAttributeNode->getValue(); } else if (XMLString::equals(attrName, XIncludeUtils::fgXIIncludeXPointerAttrName)){ xpointer = pAttributeNode->getValue(); } else if (XMLString::equals(attrName, XIncludeUtils::fgXIIncludeEncodingAttrName)){ encoding = pAttributeNode->getValue(); } else if (XMLString::equals(attrName, XIncludeUtils::fgXIIncludeAcceptAttrName)){ accept = pAttributeNode->getValue(); } else if (XMLString::equals(attrName, XIncludeUtils::fgXIIncludeAcceptLanguageAttrName)){ acceptlanguage = pAttributeNode->getValue(); } else { /* if any other attribute is in the xi namespace, it's an error */ const XMLCh *attrNamespaceURI = pAttributeNode->getNamespaceURI(); if (attrNamespaceURI && XMLString::equals(attrNamespaceURI, XIncludeUtils::fgXIIIncludeNamespaceURI)){ } else { /* ignore - any other attribute is allowed according to spec, and must be ignored */ } } } } // 3.1 xi:include Element // The children property of the xi:include element may include a single xi:fallback element; // the appearance of more than one xi:fallback element, an xi:include element, // or any other element from the XInclude namespace is a fatal error. DOMNode *child; DOMElement *fallback = NULL; for (child = xincludeNode->getFirstChild(); child != 0; child=child->getNextSibling()){ if(child->getNodeType()!=DOMNode::ELEMENT_NODE) continue; if ( isXIFallbackDOMNode(child) ){ if (fallback != NULL){ /* fatal error - there are more than one fallback children */ XIncludeUtils::reportError(xincludeNode, XMLErrs::XIncludeMultipleFallbackElems, parsedDocument->getDocumentURI(), parsedDocument->getDocumentURI()); return false; } fallback = (DOMElement*)child; } else if(isXIIncludeDOMNode(child) || XMLString::equals(child->getNamespaceURI(), XIncludeUtils::fgXIIIncludeNamespaceURI)) { /* fatal error - an xi element different from xi:fallback is a child of xi:include */ XIncludeUtils::reportError(xincludeNode, XMLErrs::XIncludeDisallowedChild, child->getNodeName(), parsedDocument->getDocumentURI()); return false; } } if (href == NULL){ /* this is an unrecoverable error until we have xpointer support - if there is an xpointer, the current document is assumed however, there is no xpointer support yet */ XIncludeUtils::reportError(xincludeNode, XMLErrs::XIncludeNoHref, NULL, parsedDocument->getDocumentURI()); return false; } /* set up the accept and accept-language values */ if (accept != NULL){ } if (parse == NULL){ /* use the default, as specified */ parse = XIncludeUtils::fgXIIncludeParseAttrXMLValue; } if (xpointer != NULL){ /* not supported yet */ /* Note that finding an xpointer attr along with parse="text" is a Fatal Error * - http://www.w3.org/TR/xinclude/#include-location */ XIncludeUtils::reportError(xincludeNode, XMLErrs::XIncludeXPointerNotSupported, NULL, href); return false; } /* set up the href according to what has gone before */ XIncludeLocation hrefLoc(href); XIncludeLocation relativeLocation(href); const XMLCh *includeBase = xincludeNode->getBaseURI(); if (includeBase != NULL){ hrefLoc.prependPath(includeBase); } if (getBaseAttrValue(xincludeNode) != NULL){ relativeLocation.prependPath(getBaseAttrValue(xincludeNode)); } /* Take the relevant action - we need to retrieve the target as a whole before we can know if it was successful or not, therefore the do* methods do not modify the parsedDocument. Swapping the results in is left to the caller (i.e. here) */ DOMText *includedText = NULL; DOMDocument *includedDoc = NULL; if (XMLString::equals(parse, XIncludeUtils::fgXIIncludeParseAttrXMLValue)){ /* including a XML element */ includedDoc = doXIncludeXMLFileDOM(hrefLoc.getLocation(), relativeLocation.getLocation(), xincludeNode, parsedDocument, entityResolver); } else if (XMLString::equals(parse, XIncludeUtils::fgXIIncludeParseAttrTextValue)){ /* including a text value */ includedText = doXIncludeTEXTFileDOM(hrefLoc.getLocation(), relativeLocation.getLocation(), encoding, xincludeNode, parsedDocument, entityResolver); } else { /* invalid parse attribute value - fatal error according to the specification */ XIncludeUtils::reportError(xincludeNode, XMLErrs::XIncludeInvalidParseVal, parse, parsedDocument->getDocumentURI()); return false; } RefVectorOf<DOMNode> delayedProcessing(12,false); if (includedDoc == NULL && includedText == NULL){ /* there was an error - this is now a resource error let's see if there is a fallback */ XIncludeUtils::reportError(xincludeNode, XMLErrs::XIncludeIncludeFailedResourceError, hrefLoc.getLocation(), parsedDocument->getDocumentURI()); if (includeParent == NULL){ includeParent = parsedDocument; } // we could be getting errors trying to insert elements at the root of the document, so we should use replaceChild; // in order to handle multiple nodes, add them to a document fragment and use that to replace the original node if (fallback){ /* baseURI fixups - see http://www.w3.org/TR/xinclude/#base for details. */ XMLUri parentURI(includeParent->getBaseURI()); XMLUri includedURI(fallback->getBaseURI()); if (fallback->hasChildNodes()){ DOMDocumentFragment* frag = parsedDocument->createDocumentFragment(); DOMNode *child = fallback->getFirstChild(); /* add the content of the fallback element, and remove the fallback elem itself */ for ( ; child != NULL ; child=child->getNextSibling()){ if (child->getNodeType() == DOMNode::DOCUMENT_TYPE_NODE){ continue; } DOMNode *newNode = parsedDocument->importNode(child, true); /* if the paths differ we need to add a base attribute */ if (newNode->getNodeType()==DOMNode::ELEMENT_NODE && !XMLString::equals(parentURI.getPath(), includedURI.getPath())){ if (getBaseAttrValue(newNode) == NULL){ /* need to calculate the proper path difference to get the relativePath */ ((DOMElement*)newNode)->setAttribute(fgXIBaseAttrName, getBaseAttrValue(fallback->getParentNode())); } else { /* the included node has base of its own which takes precedence */ XIncludeLocation xil(getBaseAttrValue(newNode)); if (getBaseAttrValue(fallback->getParentNode()) != NULL){ /* prepend any specific base modification of the xinclude node */ xil.prependPath(getBaseAttrValue(fallback->getParentNode())); } ((DOMElement*)newNode)->setAttribute(fgXIBaseAttrName, xil.getLocation()); } } DOMNode *newChild = frag->appendChild(newNode); // don't process the node now, wait until it is placed in the final position delayedProcessing.addElement(newChild); //parseDOMNodeDoingXInclude(newChild, parsedDocument, entityResolver); } includeParent->replaceChild(frag, xincludeNode); frag->release(); for(XMLSize_t i=0;i<delayedProcessing.size();i++) { DOMNode* childNode=delayedProcessing.elementAt(i); parseDOMNodeDoingXInclude(childNode, parsedDocument, entityResolver); } modifiedNode = true; } else { /* empty fallback element - simply remove it! */ includeParent->removeChild(xincludeNode); modifiedNode = true; } } else { XIncludeUtils::reportError(xincludeNode, XMLErrs::XIncludeIncludeFailedNoFallback, parsedDocument->getDocumentURI(), parsedDocument->getDocumentURI()); return false; } } else { if (includedDoc){ /* record the successful include while we process the children */ addDocumentURIToCurrentInclusionHistoryStack(hrefLoc.getLocation()); DOMDocumentFragment* frag = parsedDocument->createDocumentFragment(); /* need to import the document prolog here */ DOMNode *child = includedDoc->getFirstChild(); for (; child != NULL; child = child->getNextSibling()) { if (child->getNodeType() == DOMNode::DOCUMENT_TYPE_NODE) continue; // check for NOTATION or ENTITY clash if(child->getNodeType()==DOMNode::ELEMENT_NODE && includedDoc->getDoctype()!=NULL) { DOMNamedNodeMap *pAttributes = child->getAttributes(); XMLSize_t nSize = pAttributes->getLength(); for(XMLSize_t i=0;i<nSize;++i) { DOMAttr *pAttributeNode = (DOMAttr*) pAttributes->item(i); const DOMTypeInfo * typeInfo=pAttributeNode->getSchemaTypeInfo(); if(typeInfo && XMLString::equals(typeInfo->getTypeNamespace(), XMLUni::fgInfosetURIName)) { if(XMLString::equals(typeInfo->getTypeName(), XMLUni::fgNotationString)) { const XMLCh* notationName=pAttributeNode->getNodeValue(); DOMNotation* notat=(DOMNotation*)includedDoc->getDoctype()->getNotations()->getNamedItem(notationName); // ensure we have a DTD if(parsedDocument->getDoctype()==NULL) parsedDocument->insertBefore(parsedDocument->createDocumentType(parsedDocument->getDocumentElement()->getNodeName(), NULL,NULL), parsedDocument->getFirstChild()); DOMNotation* myNotation=(DOMNotation*)parsedDocument->getDoctype()->getNotations()->getNamedItem(notationName); if(myNotation==NULL) { // it's missing, add it parsedDocument->getDoctype()->getNotations()->setNamedItem(parsedDocument->importNode(notat, true)); } else if(XMLString::equals(myNotation->getPublicId(), notat->getPublicId()) && XMLString::equals(myNotation->getSystemId(), notat->getSystemId()) && XMLString::equals(myNotation->getBaseURI(), notat->getBaseURI())) { // it's duplicate, ignore it } else { // it's a conflict, report it XIncludeUtils::reportError(xincludeNode, XMLErrs::XIncludeConflictingNotation, notationName, parsedDocument->getDocumentURI()); } } else if(XMLString::equals(typeInfo->getTypeName(), XMLUni::fgEntityString)) { const XMLCh* entityName=pAttributeNode->getNodeValue(); DOMEntity* ent=(DOMEntity*)includedDoc->getDoctype()->getEntities()->getNamedItem(entityName); // ensure we have a DTD if(parsedDocument->getDoctype()==NULL) parsedDocument->insertBefore(parsedDocument->createDocumentType(parsedDocument->getDocumentElement()->getNodeName(), NULL,NULL), parsedDocument->getFirstChild()); DOMEntity* myEnt=(DOMEntity*)parsedDocument->getDoctype()->getEntities()->getNamedItem(entityName); if(myEnt==NULL) { // it's missing, add it parsedDocument->getDoctype()->getEntities()->setNamedItem(parsedDocument->importNode(ent, true)); } else if(XMLString::equals(myEnt->getPublicId(), ent->getPublicId()) && XMLString::equals(myEnt->getSystemId(), ent->getSystemId()) && XMLString::equals(myEnt->getBaseURI(), ent->getBaseURI())) { // it's duplicate, ignore it } else { // it's a conflict, report it XIncludeUtils::reportError(xincludeNode, XMLErrs::XIncludeConflictingEntity, entityName, parsedDocument->getDocumentURI()); } } } } } DOMNode *newNode = parsedDocument->importNode(child, true); DOMNode *newChild = frag->appendChild(newNode); // don't process the node now, wait until it is placed in the final position delayedProcessing.addElement(newChild); //parseDOMNodeDoingXInclude(newChild, parsedDocument, entityResolver); } includeParent->replaceChild(frag, xincludeNode); frag->release(); for(XMLSize_t i=0;i<delayedProcessing.size();i++) { DOMNode* childNode=delayedProcessing.elementAt(i); parseDOMNodeDoingXInclude(childNode, parsedDocument, entityResolver); } popFromCurrentInclusionHistoryStack(NULL); modifiedNode = true; } else if (includedText){ includeParent->replaceChild(includedText, xincludeNode); modifiedNode = true; } } if (includedDoc) includedDoc->release(); return modifiedNode; }
int main( ) { try { // Initialize Xerces and retrieve a DOMImplementation. XercesInitializer init; DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation( fromNative("LS").c_str( ) ); if (impl == 0) { cout << "couldn't create DOM implementation\n"; return EXIT_FAILURE; } // Construct a DOMBuilder to parse animals.xml. DOMPtr<DOMBuilder> parser = static_cast<DOMImplementationLS*>(impl)-> createDOMBuilder( DOMImplementationLS::MODE_SYNCHRONOUS, 0 ); CircusErrorHandler err; parser->setErrorHandler(&err); // Parse animals.xml. DOMDocument* doc = parser->parseURI("animals.xml"); DOMElement* animalList = doc->getDocumentElement( ); // Create XPath expression. auto_ptr<XPathEvaluator> evaluator(XPathEvaluator::createEvaluator( )); auto_ptr<XPathNSResolver> resolver(evaluator->createNSResolver(animalList)); auto_ptr<XPathExpression> xpath( evaluator->createExpression( fromNative( "animalList/animal[child::name='Herby']" ).c_str( ), resolver.get( ) ) ); auto_ptr<XPathEvaluator> evaluator(XPathEvaluator::createEvaluator( )); auto_ptr<XPathNSResolver> resolver(evaluator->createNSResolver(animalList)); auto_ptr<XPathExpression> xpath( evaluator->createExpression( fromNative("animalList/animal[child::name='Herby']").c_str( ), resolver.get( ) )); // Evaluate the expression. XPathResult* result = xpath->evaluate( doc, XPathResult::ORDERED_NODE_ITERATOR_TYPE, 0 ); DOMNode* herby; if (herby = result->iterateNext( )) { animalList->removeChild(herby); herby->release( ); // optional. } // Construct a DOMWriter to save animals.xml. DOMPtr<DOMWriter> writer = static_cast<DOMImplementationLS*>(impl)->createDOMWriter( ); writer->setErrorHandler(&err); // Save animals.xml. LocalFileFormatTarget file("circus.xml"); writer->writeNode(&file, *animalList); } catch (const DOMException& e) { cout << toNative(e.getMessage( )) << "\n"; return EXIT_FAILURE; } catch (const XPathException &e) { cout << e.getString( ) << "\n"; return EXIT_FAILURE; } catch (const exception& e) { cout << e.what( ) << "\n"; return EXIT_FAILURE; } }
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; };
//------------------------------------------------------------------------ // // 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()) { fprintf(stderr, "Test file \"%s\": Bad hex number in udata element. " "Data character number %d\n", cFileName, uData.getLen()); return false; } } // // Compare the two strings. // unsigned int i; for (i=0; i< elData.getLen(); i++) { XMLCh* elDataRaw = elData.getRawBuffer(); XMLCh* uDataRaw = uData.getRawBuffer(); if (i >= uData.getLen()) { fprintf(stderr, "Test file \"%s\": udata element shorter than data at char number %d\n", cFileName, i); writeUData(elDataRaw); return false; } if (uDataRaw[i] != elDataRaw[i]) { fprintf(stderr, "Test file \"%s\": comparison failure at character number %d\n", cFileName, i); writeUData(elDataRaw); return false; }; } if (elData.getLen() != uData.getLen()) { fprintf(stderr, "Test file \"%s\": udata element longer than data at char number %d\n", cFileName, i); writeUData(elData.getRawBuffer()); return false; } return true; }
bool XmlWorldReader::Read(const std::string &file) { // ワールドを初期化 try { initialize(); if (initFlag) { initializeWorld(); } } catch (...) { return false; } // TODO: ファイルの有無を確認 // XMLファイルをパース const XMLCh gLS[] = {chLatin_L, chLatin_S, chNull}; DOMImplementationLS *impl = DOMImplementationRegistry::getDOMImplementation(gLS); DOMLSParser *parser = impl->createLSParser( DOMImplementationLS::MODE_SYNCHRONOUS, NULL ); DOMDocument *doc = parser->parseURI(file.c_str()); if (doc == nullptr) { return false; } // rootノードを取得 DOMElement *worldElement = doc->getDocumentElement(); if (worldElement == nullptr) { parser->release(); return false; } { YPT::XmlString temp("world"); bool res = XMLString::equals(worldElement->getNodeName(), temp); if (!res) { parser->release(); return false; } } // ロード用クラス作成 YPT::XmlWorldPartReader partReader(doc); // XPathコンテキスト作成 DOMXPathNSResolver *resolver = doc->createNSResolver(worldElement); if (resolver == nullptr) { parser->release(); return false; } YPT::XmlString str, str2; DOMXPathResult *result; // -------------------------------------------------- // ワールド全体の設定 // -------------------------------------------------- // ワールド名 str = worldElement->getAttribute(YPT::XmlString("name")); if (str != "") { name = str; } // 重力ベクトル result = doc->evaluate( YPT::XmlString("./gravity"), worldElement, resolver, DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE, NULL ); if (result != nullptr) { if (result->getSnapshotLength() >= 1) { str = result->getNodeValue()->getTextContent(); b2Vec2 temp; if (!YPT::ConvertStrToVec2(str.ToChar(), &temp)) { world.SetGravity(temp); } } result->release(); } // -------------------------------------------------- // shapes // -------------------------------------------------- result = doc->evaluate( YPT::XmlString("./shape"), worldElement, resolver, DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE, NULL ); if (result != nullptr) { const XMLSize_t len = result->getSnapshotLength(); for (XMLSize_t i = 0; i < len; ++i) { result->snapshotItem(i); DOMNode *node = result->getNodeValue(); if (node == nullptr) { continue; } DOMNamedNodeMap *nodeMap = node->getAttributes(); if (nodeMap == nullptr) { continue; } DOMNode *typeNode = nodeMap->getNamedItem(YPT::XmlString("type")); if (typeNode == nullptr) { continue; } str = typeNode->getNodeValue(); b2Shape::Type type; int index; if (str == "circle") { type = b2Shape::e_circle; b2CircleShape temp; if (partReader.ReadCircleShape(node, &temp)) { circleShapes.push_back(temp); index = circleShapes.size()-1; } else { // 読み込み失敗 continue; } } else if (str == "edge") { type = b2Shape::e_edge; b2EdgeShape temp; if (partReader.ReadEdgeShape(node, &temp)) { edgeShapes.push_back(temp); index = edgeShapes.size()-1; } else { // 読み込み失敗 continue; } } else if (str == "polygon") { type = b2Shape::e_polygon; b2PolygonShape temp; if (partReader.ReadPolygonShape(node, &temp)) { polygonShapes.push_back(temp); index = polygonShapes.size()-1; } else { // 読み込み失敗 continue; } } else if (str == "chain") { type = b2Shape::e_chain; b2ChainShape temp; if (partReader.ReadChainShape(node, &temp)) { chainShapes.push_back(temp); index = chainShapes.size()-1; } else { // 読み込み失敗 continue; } } else { // 未対応 continue; } // nameプロパティがあれば保存 DOMNode *name = nodeMap->getNamedItem(YPT::XmlString("name")); if (name != nullptr) { str = name->getNodeValue(); shapes.insert(ShapesMap::value_type( std::string(str), std::make_pair(type, index) )); } } result->release(); } // -------------------------------------------------- // fixtures // -------------------------------------------------- result = doc->evaluate( YPT::XmlString("./fixture"), worldElement, resolver, DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE, NULL ); if (result != nullptr) { const XMLSize_t len = result->getSnapshotLength(); for (XMLSize_t i = 0; i < len; ++i) { result->snapshotItem(i); DOMNode *node = result->getNodeValue(); if (node == nullptr) { continue; } DOMXPathResult *result2 = doc->evaluate( YPT::XmlString("./shape"), node, resolver, DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE, NULL ); if (result2 == nullptr) { continue; } DOMNode *shapeNode = result2->getNodeValue(); if (shapeNode == nullptr) { continue; } str = shapeNode->getTextContent(); result2->release(); ShapesMap::iterator found = shapes.find(std::string(str)); if (found == shapes.end()) { continue; } // fixture読み込み b2FixtureDef fixtureDef; b2Shape *shape = NULL; int index = found->second.second; switch (found->second.first) { case b2Shape::e_circle: shape = &circleShapes[index]; break; case b2Shape::e_edge: shape = &edgeShapes[index]; break; case b2Shape::e_polygon: shape = &polygonShapes[index]; break; case b2Shape::e_chain: shape = &chainShapes[index]; break; default: // 未対応 break; } if (shape == NULL) { continue; } if (partReader.ReadFixture(node, shape, &fixtureDef)) { // 読み込み成功 // nameプロパティがあれば保存する DOMNamedNodeMap *nodeMap = node->getAttributes(); if (nodeMap == nullptr) { continue; } DOMNode *nameNode = nodeMap->getNamedItem(YPT::XmlString("name")); if (nameNode == nullptr) { continue; } str = nameNode->getNodeValue(); fixtures.insert(FixturesMap::value_type( std::string(str), fixtureDef )); } } result->release(); } // -------------------------------------------------- // bodies // -------------------------------------------------- result = doc->evaluate( YPT::XmlString("./body"), worldElement, resolver, DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE, NULL ); if (result != nullptr) { const XMLSize_t len = result->getSnapshotLength(); for (XMLSize_t i = 0; i < len; ++i) { result->snapshotItem(i); DOMNode *node = result->getNodeValue(); if (node == nullptr) { continue; } DOMXPathResult *result2 = doc->evaluate( YPT::XmlString("./fixtures/fixture"), node, resolver, DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE, NULL ); if (result2 == nullptr) { continue; } std::vector< b2FixtureDef *> fixtureDefs; const XMLSize_t fixturesLen = result2->getSnapshotLength(); for (XMLSize_t j = 0; j < fixturesLen; ++j) { result2->snapshotItem(j); DOMNode *fixtureNode = result2->getNodeValue(); if (fixtureNode == nullptr) { continue; } str = fixtureNode->getTextContent(); FixturesMap::iterator found = fixtures.find( std::string(str) ); if (found != fixtures.end()) { fixtureDefs.push_back(&found->second); } } result2->release(); b2Body *body = partReader.ReadBody(world, node, fixtureDefs); if (body != nullptr) { // 読み込み成功 // nameプロパティがあれば保存する DOMNamedNodeMap *nodeMap = node->getAttributes(); if (nodeMap == nullptr) { continue; } DOMNode *nameNode = nodeMap->getNamedItem(YPT::XmlString("name")); if (nameNode == nullptr) { continue; } str = nameNode->getNodeValue(); bodies.insert(BodiesMap::value_type( std::string(str), body )); } } result->release(); } // -------------------------------------------------- // 読み込み完了 // -------------------------------------------------- resolver->release(); parser->release(); return true; }
int main() { try { XMLPlatformUtils::Initialize(); } catch (const XMLException& toCatch) { char *pMessage = XMLString::transcode(toCatch.getMessage()); fprintf(stderr, "Error during XMLPlatformUtils::Initialize(). \n" " Message is: %s\n", pMessage); XMLString::release(&pMessage); return -1; } /* Range tests include testing of createRange setStart, setStartBefore. setStartAfter, setEnd, setEndBefore. setEndAfter getStartContainer, getStartOffset getEndContainer, getEndOffset getCommonAncestorContainer selectNode selectNodeContents insertNode deleteContents collapse getCollapsed surroundContents compareBoundaryPoints cloneRange cloneContents extractContents toString detach removeChild */ { XMLCh tempStr[100]; XMLString::transcode("Range",tempStr,99); { DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(tempStr); DOMDocument* doc = impl->createDocument(); //Creating a root element DOMElement* root = doc->createElement(xBody); doc->appendChild(root); //Creating the siblings of root DOMElement* E11 = doc->createElement(xH1); root->appendChild(E11); DOMElement* E12 = doc->createElement(xP); root->appendChild(E12); //Attaching texts to siblings DOMText* textNode1 = doc->createTextNode(xTitle); E11->appendChild(textNode1); DOMText* textNode11 = doc->createTextNode(xAnotherText); E11->appendChild(textNode11); DOMText* textNode2 = doc->createTextNode(xBlahxyz); E12->appendChild(textNode2); DOMText* E210 = doc->createTextNode(xInsertedText); doc->release(); } { //DOM Tree and some usable node creation DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(tempStr); DOMDocument* doc = impl->createDocument(); //Creating a root element DOMElement* root = doc->createElement(xBody); doc->appendChild(root); //Creating the siblings of root DOMElement* E11 = doc->createElement(xH1); root->appendChild(E11); DOMElement* E12 = doc->createElement(xP); root->appendChild(E12); //Attaching texts to siblings DOMText* textNode1 = doc->createTextNode(xTitle); E11->appendChild(textNode1); DOMText* textNode11 = doc->createTextNode(xAnotherText); E11->appendChild(textNode11); DOMText* textNode2 = doc->createTextNode(xBlahxyz); E12->appendChild(textNode2); //experimental nodes DOMElement* E120 = doc->createElement(xElement1); DOMElement* E121 = doc->createElement(xElement2); DOMElement* E122 = doc->createElement(xElement3); DOMElement* E311 = doc->createElement(xSurroundNode1); DOMText* E210 = doc->createTextNode(xInsertedText); DOMNode* rt = doc->getDocumentElement(); DOMRange* range = ((DOMDocumentRange*)doc)->createRange(); //Tests start here // Initial dom tree looks like : // <Body><H1>TitleAnother Text</H1><P>Blah xyz</P></Body> //i.e., Body(rt) // _____________|________________ // | | // ___H1(E11)___ P(E12) // | | | // "Title" "Another Text" "Blah xyz" //test for start and end settings of a range range->setStart(rt->getFirstChild(), 0); TASSERT(range->getStartContainer() == rt->getFirstChild() ); TASSERT(range->getStartOffset() == 0); range->setEnd(rt->getFirstChild(), 1); TASSERT(range->getEndContainer() == rt->getFirstChild() ); TASSERT(range->getEndOffset() == 1); //DOMNode* node = range->getCommonAncestorContainer(); TASSERT(range->getCommonAncestorContainer() == rt->getFirstChild()); //selection related test range->selectNode(rt->getLastChild()); TASSERT(range->getStartContainer() == rt); TASSERT(range->getStartOffset() == 1); TASSERT(range->getEndContainer() == rt); TASSERT(range->getEndOffset() == 2); //insertion related tests range->insertNode(E120); //only end offset moves and new node gets into range as being inserted at boundary point TASSERT(range->getStartContainer() == rt); TASSERT(range->getStartOffset() == 1); TASSERT(range->getEndContainer() == rt); TASSERT(range->getEndOffset() == 3); range->insertNode(E121); //only end offset moves and new node gets into range as being inserted at boundary point TASSERT(range->getStartContainer() == rt); TASSERT(range->getStartOffset() == 1); TASSERT(range->getEndContainer() == rt); TASSERT(range->getEndOffset() == 4); rt->insertBefore(E122, rt->getFirstChild()); //both offsets move as new node is not part of the range TASSERT(range->getStartContainer() == rt); TASSERT(range->getStartOffset() == 2); TASSERT(range->getEndContainer() == rt); TASSERT(range->getEndOffset() == 5); //After above operations, now the tree looks like: // <Body><Element3/><H1>TitleAnother Text</H1><Element2/><Element1/><P>Blah xyz</P></Body> //i.e., Body(rt) // _____________|_______________________________________________________________ // | | | | | // Element3(E122) ___H1(E11)___ Element2(E121) Element1(E120) P(E12) // | | | // "Title" "Another Text" "Blah xyz" // // range has rt as start and end container, and 2 as start offset, 5 as end offset //changing selection range->selectNode(rt->getLastChild()->getPreviousSibling()); TASSERT(range->getStartContainer() == rt); TASSERT(range->getStartOffset() == 3); TASSERT(range->getEndContainer() == rt); TASSERT(range->getEndOffset() == 4); //deleting related tests range->deleteContents(); TASSERT(rt->getLastChild()->getPreviousSibling() == E121); range->setStart(rt->getFirstChild()->getNextSibling()->getFirstChild(), 2); TASSERT(range->getStartContainer() == rt->getFirstChild()->getNextSibling()->getFirstChild()); TASSERT(!XMLString::compareString(range->getStartContainer()->getNodeValue(),xTitle)); TASSERT(range->getStartOffset() == 2); range->setEnd(rt->getFirstChild()->getNextSibling()->getFirstChild(), 4); TASSERT(range->getEndContainer() == rt->getFirstChild()->getNextSibling()->getFirstChild()); TASSERT(!XMLString::compareString(range->getEndContainer()->getNodeValue(),xTitle)); TASSERT(range->getEndOffset() == 4); TASSERT(!XMLString::compareString(range->toString(),xtl)); //inserting text between a text node range->insertNode(E210); //only end offset moves and new node gets into range as being inserted at boundary point TASSERT(range->getStartContainer() == rt->getFirstChild()->getNextSibling()->getFirstChild()); TASSERT(range->getStartOffset() == 2); TASSERT(range->getEndContainer() == rt->getFirstChild()->getNextSibling()->getLastChild()->getPreviousSibling()); TASSERT(range->getEndOffset() == 2); //inserting element node before the selected text node range->insertNode(E120); //only end offset moves and new node gets into range as being inserted at boundary point TASSERT(range->getStartContainer() == rt->getFirstChild()->getNextSibling()->getFirstChild()); TASSERT(!XMLString::compareString(range->getStartContainer()->getNodeValue(),xTi)); TASSERT(range->getStartOffset() == 2); TASSERT(range->getEndContainer() == rt->getFirstChild()->getNextSibling()->getLastChild()->getPreviousSibling()); TASSERT(!XMLString::compareString(range->getEndContainer()->getNodeValue(),xtle)); TASSERT(range->getEndOffset() == 2); TASSERT(E11->getChildNodes()->getLength()==6); //checking the text replacment range->getStartContainer()->setNodeValue(xReplacedText); //only the start offset is impact TASSERT(range->getStartContainer() == rt->getFirstChild()->getNextSibling()->getFirstChild()); TASSERT(!XMLString::compareString(range->getStartContainer()->getNodeValue(),xReplacedText)); TASSERT(range->getStartOffset() == 0); TASSERT(range->getEndContainer() == rt->getFirstChild()->getNextSibling()->getLastChild()->getPreviousSibling()); TASSERT(!XMLString::compareString(range->getEndContainer()->getNodeValue(),xtle)); TASSERT(range->getEndOffset() == 2); //After above operations, now the tree looks like: // <Body><Element3/><H1>ReplacedText<Element1/>InsertedTexttleAnother Text</H1><Element2/><P>Blah xyz</P></Body> //i.e., Body(rt) // _____________|_______________________________________________________________________________________________ // | | | | // Element3(E122) ___H1(E11)___________________________________________________________ Element2(E121) P(E12) // | | | | | | | // "ReplacedText" "" Element1(E120) "InsertedText"(E210) "tle" "Another Text" "Blah xyz" // // range has "ReplacedText" as start container and "tle" as end container // and 0 as start offset, 2 as end offset //changing the selection. Preparing for 'surround' range->setStart(range->getStartContainer()->getParentNode(), 2); range->setEnd(range->getStartContainer(), 5); TASSERT(!XMLString::compareString(range->getStartContainer()->getNodeName(),xH1)); TASSERT(!XMLString::compareString(range->getEndContainer()->getNodeName(),xH1)); TASSERT(!XMLString::compareString(range->toString(),xInsertedTexttle)); range->surroundContents(E311); TASSERT(!XMLString::compareString(range->getStartContainer()->getNodeName(),xH1)); TASSERT(range->getStartOffset() == 2); TASSERT(!XMLString::compareString(range->getEndContainer()->getNodeName(),xH1)); TASSERT(range->getEndOffset() == 3); TASSERT(E11->getChildNodes()->getLength()==4); TASSERT(E311->getChildNodes()->getLength()==3); TASSERT(!XMLString::compareString(range->toString(),xInsertedTexttle)); //After above operations, now the tree looks like: // <Body><Element3/><H1>ReplacedText<SurroundNode1><Element1/>InsertedTexttle</SurroundNode1>Another Text</H1><Element2/><P>Blah xyz</P></Body> //i.e., Body(rt) // _____________|_________________________________________________________________________ // | | | | // Element3(E122) ___H1(E11)___________________________________ Element2(E121) P(E12) // | | | | | // "ReplacedText" "" SurroundNode1(E311) "Another Text" "Blah xyz" // ____________ |_____________________________ // | | | // Element1(E120) "InsertedText"(E210) "tle" // // range has H1 as start and end container and 2 as start offset, 3 as end offset //testing cloning DOMRange* aRange = range->cloneRange(); TASSERT(aRange->getStartContainer() == range->getStartContainer()); TASSERT(aRange->getEndContainer() == range->getEndContainer()); TASSERT(aRange->getStartOffset() == 2); TASSERT(aRange->getEndOffset() == 3); //changing the new ranges start aRange->setStart(aRange->getStartContainer()->getFirstChild(), 1); //comparing the ranges short compVal = range->compareBoundaryPoints(DOMRange::END_TO_END, aRange); TASSERT(compVal == 0); compVal = range->compareBoundaryPoints(DOMRange::START_TO_START, aRange); TASSERT(compVal == 1); compVal = range->compareBoundaryPoints(DOMRange::START_TO_END, aRange); TASSERT(compVal == 1); compVal = range->compareBoundaryPoints(DOMRange::END_TO_START, aRange); TASSERT(compVal == -1); //testing collapse //not collapsed TASSERT(range->getCollapsed() == false); TASSERT(range->getStartOffset() == 2); TASSERT(range->getEndOffset() == 3); //selectNodeContents range->selectNodeContents(rt->getLastChild()->getFirstChild()); TASSERT(range->getStartContainer() == rt->getLastChild()->getFirstChild()); TASSERT(range->getEndContainer() == rt->getLastChild()->getFirstChild()); TASSERT(range->getStartOffset() == 0); TASSERT(range->getEndOffset() == 8); TASSERT(!XMLString::compareString(range->toString(),xBlahxyz)); //testing collapse range->collapse(true); //collapse to start TASSERT(range->getCollapsed() == true); TASSERT(range->getStartOffset() == 0); TASSERT(range->getEndOffset() == 0); TASSERT(!XMLString::compareString(range->toString(),XMLUni::fgZeroLenString)); TASSERT(aRange->getEndOffset() == 3); //other range is unaffected TASSERT(!XMLString::compareString(aRange->toString(),xeplacedTextInsertedTexttle)); //After above operations, now the tree looks like: // <Body><Element3/><H1>ReplacedText<SurroundNode1><Element1/>InsertedTexttle</SurroundNode1>Another Text</H1><Element2/><P>Blah xyz</P></Body> //i.e., Body(rt) // _____________|_________________________________________________________________________ // | | | | // Element3(E122) ___H1(E11)___________________________________ Element2(E121) P(E12) // | | | | | // "ReplacedText" "" SurroundNode1(E311) "Another Text" "Blah xyz" // ____________ |_____________________________ // | | | // Element1(E120) "InsertedText"(E210) "tle" // // range has "Blah xyz" as start and end container and 0 as start and end offset (collapsed) // aRange has "ReplacedText" as start container and H1 as end container // and 1 as start offset and 3 as end offset DOMDocumentFragment* docFrag = aRange->cloneContents(); TASSERT( docFrag != 0); range->selectNode(rt->getFirstChild()); TASSERT(range->getStartContainer() == rt); TASSERT(range->getEndContainer() == rt); TASSERT(range->getStartOffset() == 0); TASSERT(range->getEndOffset() == 1); //Testing toString() const XMLCh* str = aRange->toString(); TASSERT(!XMLString::compareString(str, xeplacedTextInsertedTexttle)); //start and end before and after tests range->setStartBefore(rt->getFirstChild()); TASSERT(range->getStartOffset() == 0); range->setEndBefore(rt->getFirstChild()); TASSERT(range->getEndOffset() == 0); range->setStartAfter(rt->getLastChild()); TASSERT(range->getStartOffset() == 4); range->setStartAfter(rt->getFirstChild()); TASSERT(range->getStartOffset() == 1); range->setEndBefore(rt->getLastChild()); TASSERT(range->getEndOffset() == 3); range->setEndAfter(rt->getLastChild()); TASSERT(range->getEndOffset() == 4); //testing extract() DOMDocumentFragment* frag2 = range->extractContents(); TASSERT( frag2 != 0); //After above operations, now the tree looks like: // <Body><Element3/></Body> //i.e., Body(rt) // | // Element3(E122) // // aRange has rt as start and end container, and 1 as start and end offset (collapsed) // range has rt as start and end container, and 1 as start and end offset (collapsed) // //and frag2 looks: // <Body>ReplacedText<SurroundNode1><Element1/>InsertedTexttle</SurroundNode1>Another Text</H1><Element2/><P>Blah xyz</P></Body> //i.e., Body(rt) // ______________|________________________________________________________ // | | | // ___H1(E11)___________________________________ Element2(E121) P(E12) // | | | | | //"ReplacedText" "" SurroundNode1(E311) "Another Text" "Blah xyz" // ____________ |_____________________________ // | | | // Element1(E120) "InsertedText"(E210) "tle" // //the tree do not have those node anymore after extract //only Element3 left TASSERT(rt->getChildNodes()->getLength()==1); //aRange is collapsed TASSERT(aRange->getCollapsed() == true); TASSERT(aRange->getStartContainer() == rt); TASSERT(aRange->getStartOffset() == 1); TASSERT(aRange->getEndContainer() == rt); TASSERT(aRange->getEndOffset() == 1); //range is collapsed as well TASSERT(range->getCollapsed() == true); TASSERT(range->getStartContainer() == rt); TASSERT(range->getStartOffset() == 1); TASSERT(range->getEndContainer() == rt); TASSERT(range->getEndOffset() == 1); //test the document fragment frag2 TASSERT(frag2->getChildNodes()->getLength()==3); //detaching the other range aRange->detach(); range->detach(); //*************************************************************** //another set of test //TEST createRange, setStart and setEnd, insertnode //*************************************************************** DOMImplementation* impl2 = DOMImplementationRegistry::getDOMImplementation(tempStr); DOMDocument* doc2 = impl2->createDocument(); DOMElement* root2 = doc2->createElement(xroot2); doc2->appendChild(root2); //case 1: simple text node, start==end // <body>text1</body> DOMElement* body = doc2->createElement(xBody); DOMText* text1 = doc2->createTextNode(xtext1); body->appendChild(text1); root2->appendChild(body); //set range DOMRange* range1 = doc2->createRange(); range1->setStart(text1,1); range1->setEnd(text1,3); TASSERT(!XMLString::compareString(range1->toString(),xex)); TASSERT(range1->getStartOffset()==1); TASSERT(!XMLString::compareString(range1->getStartContainer()->getNodeValue(),xtext1)); TASSERT(range1->getEndOffset()==3); TASSERT(!XMLString::compareString(range1->getEndContainer()->getNodeValue(),xtext1)); //now insert a text node //<body>ttext2ext1</body> DOMText* text2 = doc2->createTextNode(xtext2); range1->insertNode(text2); TASSERT(!XMLString::compareString(range1->toString(),xtext2ex)); TASSERT(range1->getStartOffset()==1); TASSERT(!XMLString::compareString(range1->getStartContainer()->getNodeValue(),xt)); TASSERT(range1->getEndOffset()==2); TASSERT(!XMLString::compareString(range1->getEndContainer()->getNodeValue(),xext1)); //now insert a non-text node //<body>t<p1/>text2ext1</body> DOMElement* p1 = doc2->createElement(xp1); range1->insertNode(p1); TASSERT(!XMLString::compareString(range1->toString(),xtext2ex)); TASSERT(range1->getStartOffset()==1); TASSERT(!XMLString::compareString(range1->getStartContainer()->getNodeValue(),xt)); TASSERT(range1->getEndOffset()==2); TASSERT(!XMLString::compareString(range1->getEndContainer()->getNodeValue(),xext1)); //case 2: non-text node, start==end // <head><h1/></head> DOMElement* head = doc2->createElement(xhead); DOMElement* h1 = doc2->createElement(xH1); head->appendChild(h1); root2->appendChild(head); //set range DOMRange* range2 = doc2->createRange(); range2->setStart(head,0); range2->setEnd(head,1); TASSERT(!XMLString::compareString(range2->toString(),XMLUni::fgZeroLenString)); TASSERT(range2->getStartOffset()==0); TASSERT(!XMLString::compareString(range2->getStartContainer()->getNodeName(),xhead)); TASSERT(range2->getEndOffset()==1); TASSERT(!XMLString::compareString(range2->getEndContainer()->getNodeName(),xhead)); //now insert a non-text node //<head><h2/><h1/></head> DOMElement* h2 = doc2->createElement(xh2); range2->insertNode(h2); TASSERT(!XMLString::compareString(range2->toString(),XMLUni::fgZeroLenString)); TASSERT(range2->getStartOffset()==0); TASSERT(!XMLString::compareString(range2->getStartContainer()->getNodeName(),xhead)); TASSERT(range2->getEndOffset()==2); TASSERT(!XMLString::compareString(range2->getEndContainer()->getNodeName(),xhead)); //now insert a text node //<head>text5<h2/><h1/></head> DOMText* text5 = doc2->createTextNode(xtext5); range2->insertNode(text5); TASSERT(!XMLString::compareString(range2->toString(),xtext5)); TASSERT(range2->getStartOffset()==0); TASSERT(!XMLString::compareString(range2->getStartContainer()->getNodeName(),xhead)); TASSERT(range2->getEndOffset()==3); TASSERT(!XMLString::compareString(range2->getEndContainer()->getNodeName(),xhead)); //case 3: simple text node, start!=end // <body2>text3</body2> DOMElement* body2 = doc2->createElement(xbody2); DOMText* text3 = doc2->createTextNode(xtext3); body2->appendChild(text3); root2->appendChild(body2); //set range DOMRange* range3 = ((DOMDocumentRange*)doc2)->createRange(); range3->setStart(text3,1); range3->setEnd(body2,1); TASSERT(!XMLString::compareString(range3->toString(),xext3)); TASSERT(range3->getStartOffset()==1); TASSERT(!XMLString::compareString(range3->getStartContainer()->getNodeValue(),xtext3)); TASSERT(range3->getEndOffset()==1); TASSERT(!XMLString::compareString(range3->getEndContainer()->getNodeName(),xbody2)); //now insert a textnode //<body2>ttext4ext3</body2> DOMText* text4 = doc2->createTextNode(xtext4); range3->insertNode(text4); TASSERT(!XMLString::compareString(range3->toString(),XMLUni::fgZeroLenString)); TASSERT(range3->getStartOffset()==1); TASSERT(!XMLString::compareString(range3->getStartContainer()->getNodeValue(),xt)); TASSERT(range3->getEndOffset()==1); TASSERT(!XMLString::compareString(range3->getEndContainer()->getNodeName(),xbody2)); //now insert a non-text node //<body2>t<p2/>text4ext3</body2> DOMElement* p2 = doc2->createElement(xp2); range3->insertNode(p2); //extra empty node caused by splitting 't' TASSERT(!XMLString::compareString(range3->toString(),XMLUni::fgZeroLenString)); TASSERT(range3->getStartOffset()==1); TASSERT(!XMLString::compareString(range3->getStartContainer()->getNodeValue(),xt)); TASSERT(range3->getEndOffset()==1); TASSERT(!XMLString::compareString(range3->getEndContainer()->getNodeName(),xbody2)); //test toString a bit range3->setStart(body2,1); range3->setEnd(body2,5); TASSERT(!XMLString::compareString(range3->toString(),xtext4ext3)); range3->setStart(body2,0); range3->setEnd(body2,5); TASSERT(!XMLString::compareString(range3->toString(),xttext4ext3)); //case 4: non-text node, start!=end // <head2><h3/></head2> DOMElement* head2 = doc2->createElement(xhead2); DOMElement* h3 = doc2->createElement(xh3); head2->appendChild(h3); root2->appendChild(head2); //set range DOMRange* range4 = doc2->createRange(); range4->setStart(head2,0); range4->setEnd(h3,0); TASSERT(!XMLString::compareString(range4->toString(),XMLUni::fgZeroLenString)); TASSERT(range4->getStartOffset()==0); TASSERT(!XMLString::compareString(range4->getStartContainer()->getNodeName(),xhead2)); TASSERT(range4->getEndOffset()==0); TASSERT(!XMLString::compareString(range4->getEndContainer()->getNodeName(),xh3)); //now insert a non-text node //<head2><h4/><h3/></head2> DOMElement* h4 = doc2->createElement(xh4); range4->insertNode(h4); TASSERT(!XMLString::compareString(range4->toString(),XMLUni::fgZeroLenString)); TASSERT(range4->getStartOffset()==0); TASSERT(!XMLString::compareString(range4->getStartContainer()->getNodeName(),xhead2)); TASSERT(range4->getEndOffset()==0); TASSERT(!XMLString::compareString(range4->getEndContainer()->getNodeName(),xh3)); //now insert a text node //<head2>text6<h4/><h3/></head2> DOMText* text6 = doc2->createTextNode(xtext6); range4->insertNode(text6); TASSERT(!XMLString::compareString(range4->toString(),xtext6)); TASSERT(range4->getStartOffset()==0); TASSERT(!XMLString::compareString(range4->getStartContainer()->getNodeName(),xhead2)); TASSERT(range4->getEndOffset()==0); TASSERT(!XMLString::compareString(range4->getEndContainer()->getNodeName(),xh3)); //*************************************************************** // quick test of updating //*************************************************************** // <upbody>text1</upbody> DOMElement* upbody = doc2->createElement(xupbody); DOMText* uptext1 = doc2->createTextNode(xuptext1); upbody->appendChild(uptext1); root2->appendChild(upbody); DOMRange* uprange = ((DOMDocumentRange*)doc2)->createRange(); uprange->setStart(upbody,0); uprange->setEnd(upbody,1); TASSERT(!XMLString::compareString(uprange->toString(),xuptext1)); TASSERT(uprange->getStartOffset()==0); TASSERT(!XMLString::compareString(uprange->getStartContainer()->getNodeName(),xupbody)); TASSERT(uprange->getEndOffset()==1); TASSERT(!XMLString::compareString(uprange->getEndContainer()->getNodeName(),xupbody)); // split text uptext1->splitText(1); TASSERT(!XMLString::compareString(uprange->toString(),xu)); TASSERT(uprange->getStartOffset()==0); TASSERT(!XMLString::compareString(uprange->getStartContainer()->getNodeName(),xupbody)); TASSERT(uprange->getEndOffset()==1); TASSERT(!XMLString::compareString(uprange->getEndContainer()->getNodeName(),xupbody)); //insert node DOMElement* upbody2 = doc2->createElement(xupbody2); DOMText* uptext2 = doc2->createTextNode(xuptext2); upbody2->appendChild(uptext2); root2->appendChild(upbody2); DOMRange* uprange2 = ((DOMDocumentRange*)doc2)->createRange(); uprange2->setStart(uptext2,1); uprange2->setEnd(upbody2,1); DOMRange* uprange3 = doc2->createRange(); uprange3->setStart(uptext2,1); uprange3->setEnd(upbody2,1); TASSERT(!XMLString::compareString(uprange2->toString(),xptext2)); TASSERT(uprange2->getStartOffset()==1); TASSERT(!XMLString::compareString(uprange2->getStartContainer()->getNodeValue(),xuptext2)); TASSERT(uprange2->getEndOffset()==1); TASSERT(!XMLString::compareString(uprange2->getEndContainer()->getNodeName(),xupbody2)); TASSERT(!XMLString::compareString(uprange3->toString(),xptext2)); TASSERT(uprange3->getStartOffset()==1); TASSERT(!XMLString::compareString(uprange3->getStartContainer()->getNodeValue(),xuptext2)); TASSERT(uprange3->getEndOffset()==1); TASSERT(!XMLString::compareString(uprange3->getEndContainer()->getNodeName(),xupbody2)); DOMElement* upp1 = doc2->createElement(xupp1); uprange2->insertNode(upp1); TASSERT(!XMLString::compareString(uprange2->toString(),XMLUni::fgZeroLenString)); TASSERT(uprange2->getStartOffset()==1); TASSERT(!XMLString::compareString(uprange2->getStartContainer()->getNodeValue(),xu)); TASSERT(uprange2->getEndOffset()==1); TASSERT(!XMLString::compareString(uprange2->getEndContainer()->getNodeName(),xupbody2)); TASSERT(!XMLString::compareString(uprange3->toString(),XMLUni::fgZeroLenString)); TASSERT(uprange3->getStartOffset()==1); TASSERT(!XMLString::compareString(uprange3->getStartContainer()->getNodeValue(),xu)); TASSERT(uprange3->getEndOffset()==1); TASSERT(!XMLString::compareString(uprange3->getEndContainer()->getNodeName(),xupbody2)); //*************************************************************** //another set of test //<foo><c/><moo><b/></moo>ab<a>Hello cd</a><cool>ef</cool></foo> // // ______________________foo_____________________ // | | | | | // c moo "ab" a cool // | | | // b "Hello cd" "ef" // DOMImplementation* impl3 = DOMImplementationRegistry::getDOMImplementation(tempStr); DOMDocument* doc3 = impl3->createDocument(); DOMElement* root3 = doc3->createElement(xroot); doc3->appendChild(root3); DOMElement* foo = doc3->createElement(xfoo); DOMElement* moo = doc3->createElement(xmoo); DOMElement* cool = doc3->createElement(xcool); DOMText* ab = doc3->createTextNode(xab); DOMText* cd = doc3->createTextNode(xHellocd); DOMText* ef = doc3->createTextNode(xef); DOMElement* a = doc3->createElement(xa); DOMElement* b = doc3->createElement(xb); DOMElement* c = doc3->createElement(xc); root3->appendChild(foo); foo->appendChild(c); foo->appendChild(moo); foo->appendChild(ab); foo->appendChild(a); foo->appendChild(cool); moo->appendChild(b); a->appendChild(cd); cool->appendChild(ef); //*************************************************************** //TEST toString //*************************************************************** DOMRange* newtestrange = ((DOMDocumentRange*)doc3)->createRange(); //case 1: //start container is text node // i) end container is also text node // a) start==end // b) start!=end // ii) end container is not text node // a) start==end => impossible // b) start!=end // //case 2: //start container is not text node // i) end container is text node // a) start==end => impossible // b) start!=end // ii) end container is not text node // a) start==end // b) start!=end //case 1, i, a newtestrange->setStart( cd, 1 ); newtestrange->setEnd( cd, 4 ); TASSERT(!XMLString::compareString(newtestrange->toString(),xell)); //case 1, i, b newtestrange->setStart( cd, 1 ); newtestrange->setEnd( ef, 2 ); TASSERT(!XMLString::compareString(newtestrange->toString(),xellocdef)); //case 1, ii, b newtestrange->setStart( cd, 1 ); newtestrange->setEnd( foo, 4 ); TASSERT(!XMLString::compareString(newtestrange->toString(),xellocd)); //case 2, i, b newtestrange->setStart( foo, 1 ); newtestrange->setEnd( cd, 5 ); TASSERT(!XMLString::compareString(newtestrange->toString(),xabHello)); //case 2, ii, a newtestrange->setStart( foo, 1 ); newtestrange->setEnd( foo, 4 ); TASSERT(!XMLString::compareString(newtestrange->toString(),xabHellocd)); //case 2, ii, b newtestrange->setStart( moo, 1 ); newtestrange->setEnd( foo, 4 ); TASSERT(!XMLString::compareString(newtestrange->toString(),xabHellocd)); //*************************************************************** //test removeChild //*************************************************************** DOMRange* newrange = doc3->createRange(); newrange->setStart( moo, 0 ); newrange->setEnd( foo, 4 ); TASSERT(newrange->getStartOffset()==0); TASSERT(!XMLString::compareString(newrange->getStartContainer()->getNodeName(),xmoo)); TASSERT(newrange->getEndOffset()==4); TASSERT(!XMLString::compareString(newrange->getEndContainer()->getNodeName(),xfoo)); TASSERT(!XMLString::compareString(newrange->toString(),xabHellocd)); DOMNode* n = newrange->cloneContents(); DOMNodeList* nol = foo->getChildNodes(); //removing moo DOMNode* rem = foo->removeChild(nol->item(1)); rem->release(); TASSERT(newrange->getStartOffset()==1); TASSERT(!XMLString::compareString(newrange->getStartContainer()->getNodeName(),xfoo)); TASSERT(newrange->getEndOffset()==3); TASSERT(!XMLString::compareString(newrange->getEndContainer()->getNodeName(),xfoo)); TASSERT(!XMLString::compareString(newrange->toString(),xabHellocd)); TASSERT(newtestrange->getStartOffset()==1); TASSERT(!XMLString::compareString(newtestrange->getStartContainer()->getNodeName(),xfoo)); TASSERT(newtestrange->getEndOffset()==3); TASSERT(!XMLString::compareString(newtestrange->getEndContainer()->getNodeName(),xfoo)); TASSERT(!XMLString::compareString(newtestrange->toString(),xabHellocd)); // Now do some exception test newrange->detach(); EXCEPTION_TEST(newrange->setStart( moo, 0 ), DOMException::INVALID_STATE_ERR); EXCEPTION_TEST(newtestrange->setStartBefore(moo), DOMRangeException::INVALID_NODE_TYPE_ERR); doc->release(); doc2->release(); doc3->release(); } } //creating the dom tree and tests // And call the termination method XMLPlatformUtils::Terminate(); if (errorOccurred) { printf("Test Failed\n"); return 4; } printf("Test Run Successfully\n"); return 0; };
// MÉTODO ContentRDF :: createAction int ContentRDF:: createAction(string act, string actor, vector<string> arguments, string &content) { vector<string>::iterator it; int errorCode = 0; try { // Inicialización del sistema. XMLPlatformUtils::Initialize(); } catch(const XMLException& toCatch) { char *pMsg = XMLString::transcode(toCatch.getMessage()); XERCES_STD_QUALIFIER cerr << "Error al inicializar xerces-c.\n" << " Mensaje de excepción:" << pMsg; XMLString::release(&pMsg); return 1; }// Fin catch DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(X("Core")); if (impl != NULL) { try { // *** rdf:RDF es la raíz del mensaje. DOMDocument *action = impl->createDocument(0, X("RDF"), 0); action->setEncoding(X("UTF-8")); // *** Comentario inicial. //action->createComment(X("<?xml version=\"1.0\" standalone=\"no\">")); //action->createComment(X("<!DOCTYPE fipa-message SYSTEM \"aclRep.dtd\">")); // *** Atributos de rdf:RDF. DOMElement* rootElem = action->getDocumentElement(); rootElem->setAttribute(X("xmlnsrdf"), X("http://www.w3.org/1999/02/22-rdf-syntax.ns#")); rootElem->setAttribute(X("xmlnsfipa"), X("http://www.fipa.org/schemas/fipa-rdf0#")); DOMElement* actionElem = action->createElement(X("Action")); rootElem->appendChild(actionElem); actionElem->setAttribute(X("ID"), X((actor + "Action").c_str())); // *** Actor. DOMElement* actorElem = action->createElement(X("Actor")); actionElem->appendChild(actorElem); DOMText* actorText = action->createTextNode(X(actor.c_str())); actorElem->appendChild(actorText); // *** Act. DOMElement* actElem = action->createElement(X("Act")); actionElem->appendChild(actElem); DOMText* actText = action->createTextNode(X(act.c_str())); actElem->appendChild(actText); // *** Arguments. DOMElement* argumentsElem = action->createElement(X("Argument")); actionElem->appendChild(argumentsElem); DOMElement* bagElem = action->createElement(X("Bag")); argumentsElem->appendChild(bagElem); // Lista de argumentos. DOMElement* argumentElem; DOMText* argumentText; for (it = arguments.begin(); it != arguments.end(); it++) { argumentElem = action->createElement(X("Li")); bagElem->appendChild(argumentElem); argumentText = action->createTextNode(X((*it).c_str())); argumentElem->appendChild(argumentText); }// Fin for // Serialización a través de DOMWriter XMLCh tempStr[100]; XMLString::transcode("LS", tempStr, 99); DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(tempStr); DOMWriter *theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter(); // Conversión a string XMLCh *buf = theSerializer->writeToString(*action); char *salida = XMLString::transcode(buf); string s1(salida); content = s1; XMLString::release(&buf); XMLString::release(&salida); delete theSerializer; XMLPlatformUtils::Terminate(); }// Fin try catch (const OutOfMemoryException&) { XERCES_STD_QUALIFIER cerr << "Error debido a falta de memoria." << XERCES_STD_QUALIFIER endl; errorCode = 5; }// Fin catch catch (const DOMException& e) { XERCES_STD_QUALIFIER cerr << "DOMException en: " << e.code << XERCES_STD_QUALIFIER endl; errorCode = 2; }// Fin catch catch (...) { XERCES_STD_QUALIFIER cerr << "Se produjo un error al crear el mensaje ACL." << XERCES_STD_QUALIFIER endl; errorCode = 3; }// Fin catch }// Fin if else { XERCES_STD_QUALIFIER cerr << "La implementación requerida no está disponible." << XERCES_STD_QUALIFIER endl; errorCode = 4; }// Fin else XMLPlatformUtils::Terminate(); return errorCode; }
bool ClsDataClientConfigWriter::saveConfig(string strFileName, list<ClsDataClientConfig> lstConfigs) { // cout << "ClsDataClientConfigWriter::saveConfig(string strFileName, list<ClsDataClientConfig> lstConfigs)" << endl; if(!bXMLPlatformInitialized){ try { XMLPlatformUtils::Initialize(); } catch(const XMLException& toCatch) { cerr << "Error during Xerces-c Initialization.\n" << " Exception message:" << toCatch.getMessage() << endl; bXMLPlatformInitialized = false; return false; } bXMLPlatformInitialized = true; } DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(XMLString::transcode((const char*)"Range")); DOMDocumentType *dtd = impl->createDocumentType(XMLString::transcode(ConfigTagLibrary::DataManagerConfiguration()), XMLString::transcode("-//INI/iqr421"), XMLString::transcode("iqrDataManagerConfiguration.dtd")); DOMDocument *ddocConfig = impl->createDocument(0, XMLString::transcode(ConfigTagLibrary::DataManagerConfiguration()), dtd); DOMElement *delemConfig; delemConfig = ddocConfig->getDocumentElement(); list<ClsDataClientConfig>::iterator itConfigs; for(itConfigs=lstConfigs.begin(); itConfigs != lstConfigs.end(); itConfigs++){ string strID = (*itConfigs).getID(); string strType = (*itConfigs).getType(); pair<int,int> pPosition = (*itConfigs).getPosition(); pair<int,int> pGeometry = (*itConfigs).getGeometry(); DOMElement *delemDataClient; delemDataClient = ddocConfig->createElement(XMLString::transcode(ConfigTagLibrary::DataClientTag())); delemDataClient->setAttribute(XMLString::transcode(ConfigTagLibrary::TypeTag()), XMLString::transcode(strType.c_str())); delemDataClient->setAttribute(XMLString::transcode(ConfigTagLibrary::IDTag()), XMLString::transcode(strID.c_str())); delemConfig->appendChild(delemDataClient); DOMElement *delemPosition; delemPosition = ddocConfig->createElement(XMLString::transcode(ConfigTagLibrary::PositionTag())); delemPosition->setAttribute(XMLString::transcode(ConfigTagLibrary::PositionXTag()), XMLString::transcode(iqrUtils::int2string(pPosition.first).c_str())); delemPosition->setAttribute(XMLString::transcode(ConfigTagLibrary::PositionYTag()), XMLString::transcode(iqrUtils::int2string(pPosition.second).c_str())); delemDataClient->appendChild(delemPosition); DOMElement *delemGeometry; delemGeometry = ddocConfig->createElement(XMLString::transcode(ConfigTagLibrary::Geometry())); delemGeometry->setAttribute(XMLString::transcode(ConfigTagLibrary::GeometryWidthTag()), XMLString::transcode(iqrUtils::int2string(pGeometry.first).c_str())); delemGeometry->setAttribute(XMLString::transcode(ConfigTagLibrary::GeometryHeightTag()), XMLString::transcode(iqrUtils::int2string(pGeometry.second).c_str())); delemDataClient->appendChild(delemGeometry); list<pair<string, string> > lstParameters = (*itConfigs).getListParameters(); list<pair<string, string> >::iterator itLstParameters; for(itLstParameters = lstParameters.begin(); itLstParameters != lstParameters.end(); itLstParameters++){ string strParamName = (*itLstParameters).first; string strParamValue = (*itLstParameters).second; DOMElement *delemParameter; delemParameter = ddocConfig->createElement(XMLString::transcode(strParamName.c_str())); delemDataClient->appendChild(delemParameter); DOMText *dtxtParamValue = ddocConfig->createTextNode(XMLString::transcode(strParamValue.c_str())); delemParameter->appendChild(dtxtParamValue); } DOMElement *delemSVD; delemSVD = ddocConfig->createElement(XMLString::transcode(ConfigTagLibrary::StateVariableDisplayTag())); delemDataClient->appendChild(delemSVD); list<ClsStateVariableDisplayConfig>lstSVDConfigs = (*itConfigs).getListStateVariableDisplayConfig(); list<ClsStateVariableDisplayConfig>::iterator itSVD; for(itSVD = lstSVDConfigs.begin(); itSVD != lstSVDConfigs.end(); itSVD++){ DOMElement *delemStateVariable; delemStateVariable = ddocConfig->createElement(XMLString::transcode(ConfigTagLibrary::StateVariableDisplaysTag())); delemSVD->appendChild(delemStateVariable); delemStateVariable->setAttribute(XMLString::transcode(ConfigTagLibrary::IDTag()), XMLString::transcode((*itSVD).getID().c_str())); /* delemStateVariable->setAttribute(XMLString::transcode(ConfigTagLibrary::TypeTag()), XMLString::transcode((*itSVD).getItemType().c_str())); */ delemStateVariable->setAttribute(XMLString::transcode(ConfigTagLibrary::ItemIDTag()), XMLString::transcode((*itSVD).getItemID().c_str())); delemStateVariable->setAttribute(XMLString::transcode(ConfigTagLibrary::SelectedIndicesTag()), XMLString::transcode((*itSVD).getSelectedIndices().c_str())); list<pair<string, string> > lstParametersSVD = (*itSVD).getListParameters(); list<pair<string, string> >::iterator itLstParametersSVD; for(itLstParametersSVD = lstParametersSVD.begin(); itLstParametersSVD != lstParametersSVD.end(); itLstParametersSVD++){ string strParamName = (*itLstParametersSVD).first; string strParamValue = (*itLstParametersSVD).second; DOMElement *delemParameter; delemParameter = ddocConfig->createElement(XMLString::transcode(strParamName.c_str())); delemStateVariable->appendChild(delemParameter); DOMText *dtxtParamValue = ddocConfig->createTextNode(XMLString::transcode(strParamValue.c_str())); delemParameter->appendChild(dtxtParamValue); } } } #if XERCES_VERSION_MAJOR >= 3 DOMLSSerializer* theSerializer = ((DOMImplementationLS*)impl)->createLSSerializer(); if (theSerializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true)) theSerializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true); if (theSerializer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true)) theSerializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true); #else DOMWriter* theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter(); if (theSerializer->canSetFeature(XMLUni::fgDOMWRTDiscardDefaultContent, true)) theSerializer->setFeature(XMLUni::fgDOMWRTDiscardDefaultContent, true); if (theSerializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true)) theSerializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true); #endif XMLFormatTarget *myFormTarget = new LocalFileFormatTarget(strFileName.c_str()); #if XERCES_VERSION_MAJOR >= 3 DOMLSOutput* theOutput = ((DOMImplementationLS*)impl)->createLSOutput(); theOutput->setByteStream(myFormTarget); #endif try { #if XERCES_VERSION_MAJOR >= 3 theSerializer->write(delemConfig, theOutput); #else theSerializer->writeNode(myFormTarget, *delemConfig); #endif } catch (const XMLException& toCatch) { char* message = XMLString::transcode(toCatch.getMessage()); cerr << "Exception message is: \n" << message << "\n"; XMLString::release(&message); } catch (const DOMException& toCatch) { char* message = XMLString::transcode(toCatch.msg); cerr << "Exception message is: \n" << message << "\n"; XMLString::release(&message); } catch (...) { cerr << "Unexpected Exception \n" ; } // cout << myFormTarget->getRawBuffer() << endl; theSerializer->release(); delete myFormTarget; return true; }