예제 #1
0
bool CXMLElement::ParseXML (IMemoryBlock &Stream, 
							   CXMLElement **retpElement, 
							   CString *retsError,
							   CExternalEntityTable *retEntityTable)
	{
	return ParseXML(Stream, NULL, retpElement, retsError, retEntityTable);
	}
status_t 
XMLToValue (const sptr<IByteInput>& stream, SValue &value)
{
	sptr<BCreator> creator = new BXML2ValueCreator(value, SValue::Undefined());
	BXMLIByteInputSource source(stream);
	return ParseXML(creator,&source,0);	
}
int main(int argc,char **argv)
{
 if(ParseXML(STDIN_FILENO,xml_toplevel_tags,XMLPARSE_UNKNOWN_ATTR_WARN))
    return(1);
 else
    return(0);
}
예제 #4
0
void ReadXML(const std::string& fname, Com::CObjSet<CXMLClass>& xml)
{  
  xml.Clear();
  CFileReaderXML fin(fname);
  for(;;){
    std::vector< std::pair<std::string,std::string> > aStr0;    
    if( !fin.SearchChr('<',aStr0) ) break;
    if( fin.CmpStr("<!--") ){
      std::vector< std::pair<std::string,std::string> > aStr1;      
      fin.SearchChr('>',aStr1);
      continue;
    }
    assert( fin.GetChr() == '<' );
    ParseXML(xml,fin);
  }
  const std::vector<unsigned int>& aId = xml.GetAry_ObjID();
  for(unsigned int iid=0;iid<aId.size();iid++){
    unsigned int id = aId[iid];
    const CXMLClass& cxml = xml.GetObj(id);
    std::cout << "id : " << id << std::endl;
    std::cout << "name : " << cxml.name << std::endl;
    std::cout << "member class : ";
    for(unsigned int isub=0;isub<cxml.aIdMemberClass_.size();isub++){
      std::cout << cxml.aIdMemberClass_[isub] << " ";
    }
    std::cout << std::endl;
    ////
    std::map<std::string,std::string>::const_iterator itr = cxml.mapKeyValue_.begin();
    std::cout << "property" << std::endl;
    for(;itr!=cxml.mapKeyValue_.end();itr++){
      std::cout << "  " << itr->first << " " << itr->second << std::endl;
    }
    std::cout << std::endl;
  }
}
예제 #5
0
int ParseXMLTaggingRules(const char *filename)
{
 FILE *file;
 int retval;

 if(!ExistsFile(filename))
   {
    fprintf(stderr,"Error: Specified tagging rules file '%s' does not exist.\n",filename);
    return(1);
   }

 file=fopen(filename,"r");

 if(!file)
   {
    fprintf(stderr,"Error: Cannot open tagging rules file '%s' for reading.\n",filename);
    return(1);
   }

 retval=ParseXML(file,xml_toplevel_tags,XMLPARSE_UNKNOWN_ATTR_ERRNONAME);

 fclose(file);

 if(retval)
    return(1);

 return(0);
}
예제 #6
0
int main(int argc, char **argv) {
	SpriteList sprites;

	ParseXML(strref(aXMLExample, sizeof(aXMLExample) - 1), XMLExample_Callback, &sprites);

	return 0;
}
예제 #7
0
//-----------------------------------------------------------------------------
// 讀取字串檔案
bool C_XMLString::Load(IN const nstring &szFile)
{
	TiXmlDocument ccXmlDoc;

	if(ccXmlDoc.LoadFile(C_NString(szFile).c_str()) == false)
		return C_NOutput::Instance().Error(ERRORNSTD, C_ErrorXMLString(ccXmlDoc), __T("load failed(") + szFile + __T(")"));

	ParseXML(ccXmlDoc.FirstChildElement(), nullptr, m_StringList);

	return true;
}
예제 #8
0
파일: TmxLayer.cpp 프로젝트: Alexiit/Rundom
	void TileLayer::Parse(const TiXmlNode *layerNode) 
	{
		ParseLayer(layerNode);
		// Allocate memory for reading the tiles.
		tile_map = new MapTile[GetWidth() * GetHeight()];

		const TiXmlNode *dataNode = layerNode->FirstChild("data");
		const TiXmlElement *dataElem = dataNode->ToElement();

		const char *encodingStr = dataElem->Attribute("encoding");
		const char *compressionStr = dataElem->Attribute("compression");

		// Check for encoding.
		if (encodingStr) 
		{
			if (!strcmp(encodingStr, "base64")) 
			{
				encoding = TMX_ENCODING_BASE64;
			} 
			else if (!strcmp(encodingStr, "csv")) 
			{
				encoding = TMX_ENCODING_CSV;
			}
		}

		// Check for compression.
		if (compressionStr) 
		{
			if (!strcmp(compressionStr, "gzip")) 
			{
				compression = TMX_COMPRESSION_GZIP;
			} 
			else if (!strcmp(compressionStr, "zlib")) 
			{
				compression = TMX_COMPRESSION_ZLIB;
			}
		}
		
		// Decode.
		switch (encoding) 
		{
		case TMX_ENCODING_XML:
			ParseXML(dataNode);
			break;

		case TMX_ENCODING_BASE64:
			ParseBase64(dataElem->GetText());
			break;

		case TMX_ENCODING_CSV:
			ParseCSV(dataElem->GetText());
			break;
		}
	}
예제 #9
0
unsigned int ParseXML(Com::CObjSet<CXMLClass>& xml, CFileReaderXML& fin){
  assert( fin.GetChr() == '<' ); 
  unsigned int id_this = xml.AddObj(std::make_pair(0,CXMLClass()));
  const bool is_header = ( fin.GetChr(1) == '?' );
  std::string name;
  { // extract tag name
    if( is_header ){ fin.Move(2); }
    else{ fin.Move(1); }
    name = fin.GetStrThisLine(" >\n");
    xml.GetObj(id_this).name = name;
  }
  //    std::cout << "parse xml class start : " << name << std::endl;      
  { // parse this tag 
    std::vector< std::pair<std::string,std::string> > aStr;
    if( !fin.SearchChr('>',aStr) ){ std::cout << "error : tag must be closed" << std::endl; }
    for(unsigned int istr=0;istr<aStr.size();istr++){
      std::map<std::string,std::string>& map = xml.GetObj(id_this).mapKeyValue_;
      map.insert( aStr[istr] );
    }
    if( is_header ){
      if( fin.GetChr(-1) == '?' ){ // header end here
        return id_this; 
      }
    }      
    if( fin.GetChr(-1) == '/' ){  // self-enclosing tag
      return id_this;
    }
  }
  
  { // this tag is enclosing tag
    for(;;){
      if( !fin.SearchChr('<') ){ return id_this; } // eof
      if( fin.GetChr(1) == '/' ){ // this tag ends here
        fin.Move(2);
        std::string name_e = fin.GetStrThisLine(" >\n");
        assert( name == name_e );
        fin.SearchChr('>');
        return id_this;
      }
      if( fin.CmpStr("<!--") ){ // this is comment
        fin.SearchChr('>');
        continue;
      }
      assert( fin.GetChr() == '<' );
      unsigned int id = ParseXML(xml,fin);
      xml.GetObj(id_this).aIdMemberClass_.push_back(id);
      assert( fin.GetChr() == '>' );
    }  
  }
  return id_this;
}
예제 #10
0
bool
GetXSLInput(
            XMLParserLiaison&       theLiaison,
            const XalanDOMString&   theXSLFileURL,
            XalanDOMString&         theContextNodeMatchPattern,
            XalanDOMString&         theXPathString,
            MemoryManagerType&      theMemoryManager)
{
    bool                    fResult = false;

    XalanDocument* const    theDocument =
        ParseXML(theLiaison,
                 theXSLFileURL);

    if (theDocument != 0)
    {
        const XalanDOMString    theContextNodeName("xsl:for-each", theMemoryManager);
        const XalanDOMString    theAttributeName("select", theMemoryManager);

         
        FindNodeAndGetAttributeValue(
            theDocument->getDocumentElement(),
            theContextNodeName,
            theAttributeName,
            theContextNodeMatchPattern,
            theMemoryManager);

        if (length(theContextNodeMatchPattern) != 0)
        {
            const XalanDOMString    theSelectNodeName("xsl:apply-templates", theMemoryManager);

             
            FindNodeAndGetAttributeValue(
                theDocument->getDocumentElement(),
                theSelectNodeName,
                theAttributeName,
                theXPathString,
                theMemoryManager);

            if (length(theXPathString) != 0)
            {
                fResult = true;
            }
        }
    }

    return fResult;
}
예제 #11
0
NavigationList PackageBase::NavTablesFromManifestItem(shared_ptr<PackageBase> owner, shared_ptr<ManifestItem> pItem)
{
    PackagePtr sharedPkg = std::dynamic_pointer_cast<Package>(owner);
    if ( !sharedPkg )
        return NavigationList();
    
    if ( pItem == nullptr )
        return NavigationList();
    
    xmlDocPtr doc = pItem->ReferencedDocument();
    if ( doc == nullptr )
        return NavigationList();
    
    // find each <nav> node
#if EPUB_COMPILER_SUPPORTS(CXX_INITIALIZER_LISTS)
    XPathWrangler xpath(doc, {{"epub", ePub3NamespaceURI}}); // goddamn I love C++11 initializer list constructors
#else
    XPathWrangler::NamespaceList __m;
    __m["epub"] = ePub3NamespaceURI;
    XPathWrangler xpath(doc, __m);
#endif
    xpath.NameDefaultNamespace("html");
    
    xmlNodeSetPtr nodes = xpath.Nodes("//html:nav");
    
    NavigationList tables;
    for ( int i = 0; i < nodes->nodeNr; i++ )
    {
        xmlNodePtr navNode = nodes->nodeTab[i];
        auto navTablePtr = std::make_shared<class NavigationTable>(sharedPkg, pItem->Href());
        if ( navTablePtr->ParseXML(navNode) )
            tables.push_back(navTablePtr);
    }
    
    xmlXPathFreeNodeSet(nodes);
    
    // now look for any <dl> nodes with an epub:type of "glossary"
    nodes = xpath.Nodes("//html:dl[epub:type='glossary']");
    
    return tables;
}
예제 #12
0
void Container::LoadEncryption()
{
    ContainerPtr sharedThis(shared_from_this());
    unique_ptr<ArchiveReader> pZipReader = _archive->ReaderAtPath(gEncryptionFilePath);
    if ( !pZipReader )
        return;
    
    ArchiveXmlReader reader(std::move(pZipReader));
    xmlDocPtr enc = reader.xmlReadDocument(gEncryptionFilePath, nullptr, XML_PARSE_RECOVER|XML_PARSE_NOENT|XML_PARSE_DTDATTR);
    if ( enc == nullptr )
        return;
#if EPUB_COMPILER_SUPPORTS(CXX_INITIALIZER_LISTS)
    XPathWrangler xpath(enc, {{"enc", XMLENCNamespaceURI}, {"ocf", OCFNamespaceURI}});
#else
    XPathWrangler::NamespaceList __ns;
    __ns["ocf"] = OCFNamespaceURI;
    __ns["enc"] = XMLENCNamespaceURI;
    XPathWrangler xpath(enc, __ns);
#endif
    xmlNodeSetPtr nodes = xpath.Nodes("/ocf:encryption/enc:EncryptedData");
    if ( nodes == nullptr || nodes->nodeNr == 0 )
    {
        xmlChar* mem = nullptr;
        int size = 0;
        xmlDocDumpMemory(enc, &mem, &size);
        printf("%s\n", reinterpret_cast<char*>(mem));
        xmlFree(mem);
        return;     // should be a hard error?
    }
    
    for ( int i = 0; i < nodes->nodeNr; i++ )
    {
        auto encPtr = std::make_shared<EncryptionInfo>(sharedThis);
        if ( encPtr->ParseXML(nodes->nodeTab[i]) )
            _encryption.push_back(encPtr);
    }
    
    xmlXPathFreeNodeSet(nodes);
}
예제 #13
0
int ParseOSCFile(int fd,NodesX *OSMNodes,WaysX *OSMWays,RelationsX *OSMRelations)
{
 int retval;

 /* Initialise the parser */

 InitialiseParser(OSMNodes,OSMWays,OSMRelations);

 /* Parse the file */

 nnodes=0,nways=0,nrelations=0;

 current_tags=NULL;

 retval=ParseXML(fd,xml_osc_toplevel_tags,XMLPARSE_UNKNOWN_ATTR_IGNORE);

 /* Cleanup the parser */

 CleanupParser();

 return(retval);
}
void Container::LoadEncryption()
{
    unique_ptr<ArchiveReader> pZipReader = _archive->ReaderAtPath(gEncryptionFilePath);
    if ( !pZipReader )
        return;
    
    ArchiveXmlReader reader(std::move(pZipReader));
#if EPUB_USE(LIBXML2)
    shared_ptr<xml::Document> enc = reader.xmlReadDocument(gEncryptionFilePath, nullptr, XML_PARSE_RECOVER|XML_PARSE_NOENT|XML_PARSE_DTDATTR);
#elif EPUB_USE(WIN_XML)
	auto enc = reader.ReadDocument(gEncryptionFilePath, nullptr, 0);
#endif
    if ( !bool(enc) )
        return;
#if EPUB_COMPILER_SUPPORTS(CXX_INITIALIZER_LISTS)
    XPathWrangler xpath(enc, {{"enc", XMLENCNamespaceURI}, {"ocf", OCFNamespaceURI}});
#else
    XPathWrangler::NamespaceList __ns;
    __ns["ocf"] = OCFNamespaceURI;
    __ns["enc"] = XMLENCNamespaceURI;
    XPathWrangler xpath(enc, __ns);
#endif
    xml::NodeSet nodes = xpath.Nodes("/ocf:encryption/enc:EncryptedData");
    if ( nodes.empty() )
    {
		xml::string str(enc->XMLString());
		printf("%s\n", enc->XMLString().utf8());
        return;     // should be a hard error?
    }
    
    for ( auto node : nodes )
    {
        auto encPtr = EncryptionInfo::New(Ptr());
        if ( encPtr->ParseXML(node) )
            _encryption.push_back(encPtr);
    }
}
예제 #15
0
Theme_List::Theme_List(const char * url)
{
	if (!IsNetworkInit())
		return;

	u8 *buffer = NULL;
	u32 size = 0;

	DownloadWithResponse(url, &buffer, &size);

	if(!buffer)
		return;

	const char *xml = strstr((char *) buffer, "<?xml version=");
	if(!xml)
	{
		free(buffer);
		return;
	}

	ParseXML(xml);

	free(buffer);
}
예제 #16
0
//-----------------------------------------------------------------------------
// 分析XML檔案並且增加字串
void ParseXML(IN TiXmlElement *pSource, IN nstring *pTitle, OUT std::map<nstring, nstring> &StringList)
{
	if(pSource == nullptr)
		return;

	// 建立Title字串
	nstring szTitle = nsoutf(__T("{}{}:")) << (pTitle ? *pTitle : __T("")) << pSource->Value();

	// 分析子節點
	for(TiXmlElement *pTemp = pSource->FirstChildElement(); pTemp; pTemp = pTemp->NextSiblingElement())
		ParseXML(pTemp, &szTitle, StringList);

	// 新增字串
	C_NString szID = pSource->Attribute(XMLSTRINGID);
	C_NString szText = pSource->GetText();

	if(szID.empty())
		return;

	if(szText.empty())
		return;

	StringList[szTitle + static_cast<nstring>(szID)] = szText;
}
예제 #17
0
int GetGameXML(ConfigSettings *cs, GameInfo *game, char *emulator) {
	int c1=0;
	FILE *pi;
	char temp[20000]={'\x00'};
	char c;
	char *ptr;
	xmlDocPtr xmlbuffer = NULL;
	char cmd[255];

	if (!strcmp(game->name, ""))
		return 1;

	/* Windows needs a kludge I guess */
	if (IS_WIN) {
		char* argv[25];
		FILE *fp = NULL;
		char file[255];
        	pid_t cpid;
        	pid_t child_pid;

		sprintf(file, "%s.xml", game->name);
		
		//system(cmd);
		sprintf(cmd, "%s", emulator);
		argv[0] = emulator;
		argv[1] = "-listxml";
		argv[2] = game->name;
		argv[3] = NULL;

        	/* Fork and run mame, wait for pid to exit */
        	cpid = fork();
        	switch (cpid) {
                	case -1: printf("Failed running %s\n", emulator);
                	break;
        	case 0: child_pid = getpid();
			fp = freopen(file, "w", stdout);
                	execvp(emulator, argv);
			{
				char *path = NULL;
				char *envp = getenv("PATH");
				path = strtok(envp, ":");
				while(path != NULL) {
					char executable[255];
					sprintf(executable, "%s/%s", path, emulator);
                			execvp(executable, argv);
					if (cs->verbose > 2)
						sr_fprintf(stderr, "Failed running %s\n", executable);
					path = strtok(NULL, ":");
				}
			}
			sr_fprintf(stderr, "%s exited or failed running with PATH=%s\n", emulator, getenv("PATH"));
                	exit(1); // Failed
        	default:
                	waitpid(cpid, NULL, 0);
                	break;
        	}
		if (fp)
			fclose(fp);

		xmlbuffer = xmlParseFile(file);
		unlink(file);
		if (xmlbuffer == NULL)
			return -1;
		ParseXML(xmlbuffer, game, cs);
		xmlFreeDoc(xmlbuffer);
		if (game->width <= 0 || game->height <= 0 || game->refresh <= 0)
			return -1;
		return 0;
	} else
		sprintf(cmd, "%s -listxml %s", emulator, game->name);

	pi=popen(cmd, "r");
	if(pi != NULL) {
		int i = 0;
        	c=fgetc(pi);
        	while(c != '\xff' && i < 20000) {
                	temp[c1]=c;
                	c=fgetc(pi);
                	c1++;
                }
        	temp[c1]='\x00';
        	pclose(pi);

		if (cs->verbose > 3)
			sr_fprintf(stderr, "Game XML is: %s\n", temp);

		/* Turn into an XML buffer */
		ptr = (char *) &temp;
		xmlbuffer = xmlParseDoc(xmlCharStrdup(ptr));
		if (xmlbuffer == NULL) {
			sr_fprintf(stderr, "Error getting XML info for %s from %s\n",
				emulator, game->name);
			return -1;
		}
		ParseXML(xmlbuffer, game, cs);

		xmlFreeDoc(xmlbuffer);
        }

	if (game->width <= 0 || game->height <= 0 || game->refresh <= 0) {
		if (cs->verbose > 2)
			sr_fprintf(stderr, "Didn't get width/height/refresh from mame\n");
		return -1;
	}

	return 0;
}
예제 #18
0
/**
* 初始化
* @param void
* @return void
*/
void CMuteList::OnInit()
{
	// 解析配置文件
	ParseXML();
}
/**
* 初始化
* @param void
* @return void
*/
void CTestLimitList::OnInit()
{
	// 解析配置文件
	ParseXML();
}
/**
* 初始化
* @param void
* @return void
*/
void CPointCodeList::OnInit()
{
	m_uiCountAll = 0;	// 点代码总数	
	ParseXML();	// 解析配置文件
}
예제 #21
0
파일: TmxLayer.cpp 프로젝트: skryabiin/core
	void Layer::Parse(const TiXmlNode *layerNode) 
	{
		const TiXmlElement *layerElem = layerNode->ToElement();
	
		// Read the attributes.
		name = layerElem->Attribute("name");

		layerElem->Attribute("width", &width);
		layerElem->Attribute("height", &height);

		const char *opacityStr = layerElem->Attribute("opacity");
		if (opacityStr) 
		{
			opacity = (float)atof(opacityStr);
		}

		const char *visibleStr = layerElem->Attribute("visible");
		if (visibleStr) 
		{
			visible = atoi(visibleStr) != 0; // to prevent visual c++ from complaining..
		}

		// Read the properties.
		const TiXmlNode *propertiesNode = layerNode->FirstChild("properties");
		if (propertiesNode) 
		{
			properties.Parse(propertiesNode);
		}

		// Allocate memory for reading the tiles.
		tile_map = new MapTile[width * height];

		const TiXmlNode *dataNode = layerNode->FirstChild("data");
		const TiXmlElement *dataElem = dataNode->ToElement();

		const char *encodingStr = dataElem->Attribute("encoding");
		const char *compressionStr = dataElem->Attribute("compression");

		// Check for encoding.
		if (encodingStr) 
		{
			if (!strcmp(encodingStr, "base64")) 
			{
				encoding = TMX_ENCODING_BASE64;
			} 
			else if (!strcmp(encodingStr, "csv")) 
			{
				encoding = TMX_ENCODING_CSV;
			}
		}

		// Check for compression.
		if (compressionStr) 
		{
			if (!strcmp(compressionStr, "gzip")) 
			{
				compression = TMX_COMPRESSION_GZIP;
			} 
			else if (!strcmp(compressionStr, "zlib")) 
			{
				compression = TMX_COMPRESSION_ZLIB;
			}
		}
		
		// Decode.
		switch (encoding) 
		{
		case TMX_ENCODING_XML:
			ParseXML(dataNode);
			break;

		case TMX_ENCODING_BASE64:
			ParseBase64(dataElem->GetText());
			break;

		case TMX_ENCODING_CSV:
			ParseCSV(dataElem->GetText());
			break;
		}
	}
예제 #22
0
int main(int argc,char **argv)
{
 int i,j;

 /* Parse the XSD file */

 if(ParseXML(STDIN_FILENO,xml_toplevel_tags,XMLPARSE_UNKNOWN_ATTR_IGNORE))
   {
    fprintf(stderr,"Cannot parse XML file - exiting.\n");
    exit(1);
   }

 /* Print the header */

 printf("/***************************************\n");
 printf(" An automatically generated skeleton XML parser.\n");
 printf("\n");
 printf(" Automatically generated by xsd-to-xmlparser.\n");
 printf(" ***************************************/\n");
 printf("\n");
 printf("\n");
 printf("#include <stdio.h>\n");
 printf("#if !defined(_MSC_VER)\n");
 printf("#include <unistd.h>\n");
 printf("#endif\n");
 printf("\n");
 printf("#include \"xmlparse.h\"\n");

 /* Print the function prototypes */

 printf("\n");
 printf("\n");
 printf("/* The XML tag processing function prototypes */\n");
 printf("\n");

 for(i=0;i<ntagsx;i++)
   {
    printf("static int %s_function(const char *_tag_,int _type_",safe(tagsx[i]->type));

    for(j=0;j<tagsx[i]->nattributes;j++)
       printf(",const char *%s",safe(tagsx[i]->attributes[j]));

    printf(");\n");
   }

 /* Print the xmltag variables */

 printf("\n");
 printf("\n");
 printf("/* The XML tag definitions (forward declarations) */\n");

 printf("\n");

 for(i=0;i<ntagsx;i++)
    printf("static const xmltag %s_tag;\n",safe(tagsx[i]->type));

 printf("\n");
 printf("\n");
 printf("/* The XML tag definition values */\n");

 printf("\n");
 printf("/*+ The complete set of tags at the top level. +*/\n");
 printf("static const xmltag * const xml_toplevel_tags[]={");
 printf("&%s_tag,",safe(tagsx[0]->type));
 printf("&%s_tag,",safe(tagsx[1]->type));
 printf("NULL};\n");

 for(i=0;i<ntagsx;i++)
   {
    printf("\n");
    printf("/*+ The %s type tag. +*/\n",tagsx[i]->type);
    printf("static const xmltag %s_tag=\n",safe(tagsx[i]->type));
    printf("              {\"%s\",\n",tagsx[i]->name);

    printf("               %d, {",tagsx[i]->nattributes);
    for(j=0;j<tagsx[i]->nattributes;j++)
       printf("%s\"%s\"",(j?",":""),tagsx[i]->attributes[j]);
    printf("%s},\n",(tagsx[i]->nattributes?"":"NULL"));

    printf("               %s_function,\n",safe(tagsx[i]->type));

    printf("               {");
    for(j=0;j<tagsx[i]->nsubtagsx;j++)
       printf("&%s_tag,",safe(tagsx[i]->subtagsx[j]->type));
    printf("NULL}};\n");
   }

 /* Print the functions */

 printf("\n");
 printf("\n");
 printf("/* The XML tag processing functions */\n");

 for(i=0;i<ntagsx;i++)
   {
    printf("\n");
    printf("\n");
    printf("/*++++++++++++++++++++++++++++++++++++++\n");
    if(i==0) /* XML tag */
       printf("  The function that is called when the XML declaration is seen\n");
    else
       printf("  The function that is called when the %s XSD type is seen\n",tagsx[i]->type);
    printf("\n");
    printf("  int %s_function Returns 0 if no error occured or something else otherwise.\n",safe(tagsx[i]->type));
    printf("\n");
    printf("  const char *_tag_ Set to the name of the element tag that triggered this function call.\n");
    printf("\n");
    printf("  int _type_ Set to XMLPARSE_TAG_START at the start of a tag and/or XMLPARSE_TAG_END at the end of a tag.\n");
    for(j=0;j<tagsx[i]->nattributes;j++)
      {
       printf("\n");
       printf("  const char *%s The contents of the '%s' attribute (or NULL if not defined).\n",safe(tagsx[i]->attributes[j]),tagsx[i]->attributes[j]);
      }
    printf("  ++++++++++++++++++++++++++++++++++++++*/\n");
    printf("\n");

    printf("static int %s_function(const char *_tag_,int _type_",safe(tagsx[i]->type));

    for(j=0;j<tagsx[i]->nattributes;j++)
       printf(",const char *%s",safe(tagsx[i]->attributes[j]));

    printf(")\n");

    printf("{\n");

    if(i==(ntagsx-1))            /* XML tag */
      {
       printf(" printf(\"<?%%s\",_tag_);\n");
       for(j=0;j<tagsx[i]->nattributes;j++)
         {
          char *safename=safe(tagsx[i]->attributes[j]);
          printf(" if(%s) printf(\" %s=\\\"%%s\\\"\",ParseXML_Encode_Safe_XML(%s));\n",safename,tagsx[i]->attributes[j],safename);
         }
       printf(" printf(\" ?>\\n\");\n");
      }
    else
      {
       printf(" printf(\"<%%s%%s\",(_type_==XMLPARSE_TAG_END)?\"/\":\"\",_tag_);\n");
       for(j=0;j<tagsx[i]->nattributes;j++)
         {
          char *safename=safe(tagsx[i]->attributes[j]);
          printf(" if(%s) printf(\" %s=\\\"%%s\\\"\",ParseXML_Encode_Safe_XML(%s));\n",safename,tagsx[i]->attributes[j],safename);
         }
       printf(" printf(\"%%s>\\n\",(_type_==(XMLPARSE_TAG_START|XMLPARSE_TAG_END))?\" /\":\"\");\n");
      }

    printf(" return(0);\n");
    printf("}\n");
   }

 /* Print the main function */

 printf("\n");
 printf("\n");
 printf("/*++++++++++++++++++++++++++++++++++++++\n");
 printf("  A skeleton XML parser.\n");
 printf("  ++++++++++++++++++++++++++++++++++++++*/\n");
 printf("\n");
 printf("int main(int argc,char **argv)\n");
 printf("{\n");
 printf(" if(ParseXML(STDIN_FILENO,xml_toplevel_tags,XMLPARSE_UNKNOWN_ATTR_WARN))\n");
 printf("    return(1);\n");
 printf(" else\n");
 printf("    return(0);\n");
 printf("}\n");

 return(0);
}
예제 #23
0
long
LoadDriverPList( char * dirSpec, char * name, long bundleType )
{
	long      length, executablePathLength, bundlePathLength;
	ModulePtr module;
	TagPtr    personalities;
	char *    buffer = 0;
	char *    tmpExecutablePath = 0;
	char *    tmpBundlePath = 0;
	long      ret = -1;

	do{
	// Save the driver path.
        
	if(name) {
		snprintf(gFileSpec, 4096, "%s/%s/%s", dirSpec, name, (bundleType == kCFBundleType2) ? "Contents/MacOS/" : "");
	} else {
		snprintf(gFileSpec, 4096, "%s/%s", dirSpec, (bundleType == kCFBundleType2) ? "Contents/MacOS/" : "");
	}
	executablePathLength = strlen(gFileSpec) + 1;

	tmpExecutablePath = malloc(executablePathLength);
	if (tmpExecutablePath == 0) {
		break;
	}
	strcpy(tmpExecutablePath, gFileSpec);

	if(name) {
		snprintf(gFileSpec, 4096, "%s/%s", dirSpec, name);
	} else 	{
		snprintf(gFileSpec, 4096, "%s", dirSpec);
	}
	bundlePathLength = strlen(gFileSpec) + 1;

	tmpBundlePath = malloc(bundlePathLength);
	if (tmpBundlePath == 0) {
		break;
	}

	strcpy(tmpBundlePath, gFileSpec);

	// Construct the file spec to the plist, then load it.

	if(name) {
		snprintf(gFileSpec, 4096, "%s/%s/%sInfo.plist", dirSpec, name, (bundleType == kCFBundleType2) ? "Contents/" : "");
	} else {
		snprintf(gFileSpec, 4096, "%s/%sInfo.plist", dirSpec, (bundleType == kCFBundleType2) ? "Contents/" : "");
	}

	length = LoadFile(gFileSpec);
	if (length == -1) {
		break;
	}
	length = length + 1;
	buffer = malloc(length);
	if (buffer == 0) {
		break;
	}
	strlcpy(buffer, (char *)kLoadAddr, length);

	// Parse the plist.

	ret = ParseXML(buffer, &module, &personalities);

	if (ret != 0) {
		break;
	}

	if (!module) // cparm
	{
		ret = -1;
		break;
	} // Should never happen but it will make the compiler happy

	// Allocate memory for the driver path and the plist.

	module->executablePath = tmpExecutablePath;
	module->bundlePath = tmpBundlePath;
	module->bundlePathLength = bundlePathLength;
	module->plistAddr = malloc(length);

	if ((module->executablePath == 0) || (module->bundlePath == 0) || (module->plistAddr == 0)) {
		break;
	}

	// Save the driver path in the module.
	//strcpy(module->driverPath, tmpDriverPath);
	tmpExecutablePath = 0;
	tmpBundlePath = 0;

	// Add the plist to the module.

	strlcpy(module->plistAddr, (char *)kLoadAddr, length);
	module->plistLength = length;

	// Add the module to the end of the module list.
        
	if (gModuleHead == 0) {
		gModuleHead = module;
	} else 	{
		gModuleTail->nextModule = module;
	}
	gModuleTail = module;

	// Add the persionalities to the personality list.

	if (personalities) {
		personalities = personalities->tag;
	}
	while (personalities != 0)
	{
		if (gPersonalityHead == 0) {
			gPersonalityHead = personalities->tag;
		} else {
			gPersonalityTail->tagNext = personalities->tag;
		}

		gPersonalityTail = personalities->tag;
		personalities = personalities->tagNext;
	}
        
	ret = 0;
	}
	while (0);
    
	if ( buffer ) {
		free( buffer );
	}
	if ( tmpExecutablePath ) {
		free( tmpExecutablePath );
	}
	if ( tmpBundlePath ) {
		free( tmpBundlePath );
	}
	return ret;
}
예제 #24
0
/**
* 初始化
* @param void
* @return void
*/
void CMarkerList::OnInit()
{
	// 解析配置文件
	ParseXML();
}
예제 #25
0
    void TileLayer::Parse(const tinyxml2::XMLNode *tileLayerNode) 
    {
        const tinyxml2::XMLElement *tileLayerElem = tileLayerNode->ToElement();
    
        // Read the attributes.
        name = tileLayerElem->Attribute("name");

        tileLayerElem->QueryIntAttribute("x", &x);
        tileLayerElem->QueryIntAttribute("y", &y);

        tileLayerElem->QueryFloatAttribute("opacity", &opacity);
        tileLayerElem->QueryBoolAttribute("visible", &visible);

        // Read the properties.
        const tinyxml2::XMLNode *propertiesNode = tileLayerNode->FirstChildElement("properties");
        if (propertiesNode) 
        {
            properties.Parse(propertiesNode);
        }

        // Allocate memory for reading the tiles.
        tile_map = new MapTile[width * height];

        //const tinyxml2::XMLNode *dataNode = tileLayerNode->FirstChildElement("data");
        const tinyxml2::XMLElement *dataElem = tileLayerNode->FirstChildElement("data");

        const char *encodingStr = dataElem->Attribute("encoding");
        const char *compressionStr = dataElem->Attribute("compression");

        // Check for encoding.
        if (encodingStr) 
        {
            if (!strcmp(encodingStr, "base64")) 
            {
                encoding = TMX_ENCODING_BASE64;
            } 
            else if (!strcmp(encodingStr, "csv")) 
            {
                encoding = TMX_ENCODING_CSV;
            }
        }

        // Check for compression.
        if (compressionStr) 
        {
            if (!strcmp(compressionStr, "gzip")) 
            {
                compression = TMX_COMPRESSION_GZIP;
            } 
            else if (!strcmp(compressionStr, "zlib")) 
            {
                compression = TMX_COMPRESSION_ZLIB;
            }
        }
        
        // Decode.
        switch (encoding) 
        {
        case TMX_ENCODING_XML:
            ParseXML(dataElem);
            break;

        case TMX_ENCODING_BASE64:
            ParseBase64(dataElem->GetText());
            break;

        case TMX_ENCODING_CSV:
            ParseCSV(dataElem->GetText());
            break;
        }
    }
예제 #26
0
bool Package::Unpack()
{
    PackagePtr sharedMe = shared_from_this();
    
    // very basic sanity check
    xmlNodePtr root = xmlDocGetRootElement(_opf);
    string rootName(reinterpret_cast<const char*>(root->name));
    rootName.tolower();
    
    if ( rootName != "package" )
    {
        HandleError(EPUBError::OPFInvalidPackageDocument);
        return false;       // not an OPF file, innit?
    }
    if ( _getProp(root, "version").empty() )
    {
        HandleError(EPUBError::OPFPackageHasNoVersion);
    }
    
    InstallPrefixesFromAttributeValue(_getProp(root, "prefix", ePub3NamespaceURI));
    
    // go through children to determine the CFI index of the <spine> tag
    static const xmlChar* kSpineName = BAD_CAST "spine";
    static const xmlChar* kManifestName = BAD_CAST "manifest";
    static const xmlChar* kMetadataName = BAD_CAST "metadata";
    _spineCFIIndex = 0;
    uint32_t idx = 0;
    xmlNodePtr child = xmlFirstElementChild(root);
    while ( child != nullptr )
    {
        idx += 2;
        if ( xmlStrEqual(child->name, kSpineName) )
        {
            _spineCFIIndex = idx;
            if ( _spineCFIIndex != 6 )
                HandleError(EPUBError::OPFSpineOutOfOrder);
        }
        else if ( xmlStrEqual(child->name, kManifestName) && idx != 4 )
        {
            HandleError(EPUBError::OPFManifestOutOfOrder);
        }
        else if ( xmlStrEqual(child->name, kMetadataName) && idx != 2 )
        {
            HandleError(EPUBError::OPFMetadataOutOfOrder);
        }
        
        child = xmlNextElementSibling(child);
    }
    
    if ( _spineCFIIndex == 0 )
    {
        HandleError(EPUBError::OPFNoSpine);
        return false;       // spineless!
    }
    
#if EPUB_COMPILER_SUPPORTS(CXX_INITIALIZER_LISTS)
    XPathWrangler xpath(_opf, {{"opf", OPFNamespace}, {"dc", DCNamespace}});
#else
    XPathWrangler::NamespaceList __m;
    __m["opf"] = OPFNamespace;
    __m["dc"] = DCNamespace;
    XPathWrangler xpath(_opf, __m);
#endif
    
    // simple things: manifest and spine items
    xmlNodeSetPtr manifestNodes = nullptr;
    xmlNodeSetPtr spineNodes = nullptr;
    
    try
    {
        manifestNodes = xpath.Nodes("/opf:package/opf:manifest/opf:item");
        spineNodes = xpath.Nodes("/opf:package/opf:spine/opf:itemref");
        
        if ( manifestNodes == nullptr )
        {
            HandleError(EPUBError::OPFNoManifestItems);
        }
        
        if ( spineNodes == nullptr )
        {
            HandleError(EPUBError::OPFNoSpineItems);
        }
        
        for ( int i = 0; i < manifestNodes->nodeNr; i++ )
        {
            auto p = std::make_shared<ManifestItem>(sharedMe);
            if ( p->ParseXML(p, manifestNodes->nodeTab[i]) )
            {
#if EPUB_HAVE(CXX_MAP_EMPLACE)
                _manifest.emplace(p->Identifier(), p);
#else
                _manifest[p->Identifier()] = p;
#endif
                StoreXMLIdentifiable(p);
            }
            else
            {
                // TODO: Need an error here
            }
        }
        
        // check fallback chains
        typedef std::map<string, bool> IdentSet;
        IdentSet idents;
        for ( auto &pair : _manifest )
        {
            ManifestItemPtr item = pair.second;
            if ( item->FallbackID().empty() )
                continue;
            
            idents[item->XMLIdentifier()] = true;
            while ( !item->FallbackID().empty() )
            {
                if ( idents[item->FallbackID()] )
                {
                    HandleError(EPUBError::OPFFallbackChainCircularReference);
                    break;
                }
                
                item = item->Fallback();
            }
            
            idents.clear();
        }
        
        SpineItemPtr cur;
        for ( int i = 0; i < spineNodes->nodeNr; i++ )
        {
            auto next = std::make_shared<SpineItem>(sharedMe);
            if ( next->ParseXML(next, spineNodes->nodeTab[i]) == false )
            {
                // TODO: need an error code here
                continue;
            }
            
            // validation of idref
            auto manifestFound = _manifest.find(next->Idref());
            if ( manifestFound == _manifest.end() )
            {
                HandleError(EPUBError::OPFInvalidSpineIdref, _Str(next->Idref(), " does not correspond to a manifest item"));
                continue;
            }
            
            // validation of spine resource type w/fallbacks
            ManifestItemPtr manifestItem = next->ManifestItem();
            bool isContentDoc = false;
            do
            {
                if ( manifestItem->MediaType() == "application/xhtml+xml" ||
                     manifestItem->MediaType() == "image/svg" )
                {
                    isContentDoc = true;
                    break;
                }
                
            } while ( (manifestItem = manifestItem->Fallback()) );
            
            if ( !isContentDoc )
                HandleError(EPUBError::OPFFallbackChainHasNoContentDocument);
            
            StoreXMLIdentifiable(next);
            
            if ( cur != nullptr )
            {
                cur->SetNextItem(next);
            }
            else
            {
                _spine = next;
            }
            
            cur = next;
        }
    }
    catch (const std::system_error& exc)
    {
        if ( manifestNodes != nullptr )
            xmlXPathFreeNodeSet(manifestNodes);
        if ( spineNodes != nullptr )
            xmlXPathFreeNodeSet(spineNodes);
        if ( exc.code().category() == epub_spec_category() )
            throw;
        return false;
    }
    catch (...)
    {
        if ( manifestNodes != nullptr )
            xmlXPathFreeNodeSet(manifestNodes);
        if ( spineNodes != nullptr )
            xmlXPathFreeNodeSet(spineNodes);
        return false;
    }
    
    xmlXPathFreeNodeSet(manifestNodes);
    xmlXPathFreeNodeSet(spineNodes);
    
    // now the metadata, which is slightly more involved due to extensions
    xmlNodeSetPtr metadataNodes = nullptr;
    xmlNodeSetPtr refineNodes = xmlXPathNodeSetCreate(nullptr);
    
    try
    {
        shared_ptr<PropertyHolder> holderPtr = std::dynamic_pointer_cast<PropertyHolder>(sharedMe);
        metadataNodes = xpath.Nodes("/opf:package/opf:metadata/*");
        if ( metadataNodes == nullptr )
            HandleError(EPUBError::OPFNoMetadata);
        
        bool foundIdentifier = false, foundTitle = false, foundLanguage = false, foundModDate = false;
        string uniqueIDRef = _getProp(root, "unique-identifier");
        if ( uniqueIDRef.empty() )
            HandleError(EPUBError::OPFPackageUniqueIDInvalid);
        
        for ( int i = 0; i < metadataNodes->nodeNr; i++ )
        {
            xmlNodePtr node = metadataNodes->nodeTab[i];
            PropertyPtr p;
            
            if ( node->ns != nullptr && xmlStrcmp(node->ns->href, BAD_CAST DCNamespace) == 0 )
            {
                // definitely a main node
                p = std::make_shared<Property>(holderPtr);
            }
            else if ( _getProp(node, "name").size() > 0 )
            {
                // it's an ePub2 item-- ignore it
                continue;
            }
            else if ( _getProp(node, "refines").empty() )
            {
                // not refining anything, so it's a main node
                p = std::make_shared<Property>(holderPtr);
            }
            else
            {
                // by elimination it's refining something-- we'll process it later when we know we've got all the main nodes in there
                xmlXPathNodeSetAdd(refineNodes, node);
            }
            
            if ( p && p->ParseMetaElement(node) )
            {
                switch ( p->Type() )
                {
                    case DCType::Identifier:
                    {
                        foundIdentifier = true;
                        if ( !uniqueIDRef.empty() && uniqueIDRef != p->XMLIdentifier() )
                            HandleError(EPUBError::OPFPackageUniqueIDInvalid);
                        break;
                    }
                    case DCType::Title:
                    {
                        foundTitle = true;
                        break;
                    }
                    case DCType::Language:
                    {
                        foundLanguage = true;
                        break;
                    }
                    case DCType::Custom:
                    {
                        if ( p->PropertyIdentifier() == MakePropertyIRI("modified", "dcterms") )
                            foundModDate = true;
                        break;
                    }
                        
                    default:
                        break;
                }
                
                AddProperty(p);
                StoreXMLIdentifiable(p);
            }
        }
        
        if ( !foundIdentifier )
            HandleError(EPUBError::OPFMissingIdentifierMetadata);
        if ( !foundTitle )
            HandleError(EPUBError::OPFMissingTitleMetadata);
        if ( !foundLanguage )
            HandleError(EPUBError::OPFMissingLanguageMetadata);
        if ( !foundModDate )
            HandleError(EPUBError::OPFMissingModificationDateMetadata);
        
        for ( int i = 0; i < refineNodes->nodeNr; i++ )
        {
            xmlNodePtr node = refineNodes->nodeTab[i];
            string ident = _getProp(node, "refines");
            if ( ident.empty() )
            {
                HandleError(EPUBError::OPFInvalidRefinementAttribute, "Empty IRI for 'refines' attribute");
                continue;
            }
            
            if ( ident[0] == '#' )
            {
                ident = ident.substr(1);
            }
            else
            {
                // validation only right now
                IRI iri(ident);
                if ( iri.IsEmpty() )
                {
                    HandleError(EPUBError::OPFInvalidRefinementAttribute, _Str("#", ident, " is not a valid IRI"));
                }
                else if ( iri.IsRelative() == false )
                {
                    HandleError(EPUBError::OPFInvalidRefinementAttribute, _Str(iri.IRIString(), " is not a relative IRI"));
                }
                continue;
            }
            
            auto found = _xmlIDLookup.find(ident);
            if ( found == _xmlIDLookup.end() )
            {
                HandleError(EPUBError::OPFInvalidRefinementTarget, _Str("#", ident, " does not reference an item in this document"));
                continue;
            }
            
            PropertyPtr prop = std::dynamic_pointer_cast<Property>(found->second);
            if ( prop )
            {
                // it's a property, so this is an extension
                PropertyExtensionPtr extPtr = std::make_shared<PropertyExtension>(prop);
                if ( extPtr->ParseMetaElement(node) )
                    prop->AddExtension(extPtr);
            }
            else
            {
                // not a property, so treat this as a plain property
                shared_ptr<PropertyHolder> ptr = std::dynamic_pointer_cast<PropertyHolder>(found->second);
                if ( ptr )
                {
                    prop = std::make_shared<Property>(ptr);
                    if ( prop->ParseMetaElement(node) )
                        ptr->AddProperty(prop);
                }
            }
        }
        
        // now look at the <spine> element for properties
        xmlNodePtr spineNode = xmlFirstElementChild(root);
        for ( uint32_t i = 2; i < _spineCFIIndex; i += 2 )
            spineNode = xmlNextElementSibling(spineNode);
        
        string value = _getProp(spineNode, "page-progression-direction");
        if ( !value.empty() )
        {
            PropertyPtr prop = std::make_shared<Property>(holderPtr);
            prop->SetPropertyIdentifier(MakePropertyIRI("page-progression-direction"));
            prop->SetValue(value);
            AddProperty(prop);
        }
    }
    catch (std::system_error& exc)
    {
        if ( metadataNodes != nullptr )
            xmlXPathFreeNodeSet(metadataNodes);
        if ( refineNodes != nullptr )
            xmlXPathFreeNodeSet(refineNodes);
        if ( exc.code().category() == epub_spec_category() )
            throw;
        return false;
    }
    catch (...)
    {
        if ( metadataNodes != nullptr )
            xmlXPathFreeNodeSet(metadataNodes);
        if ( refineNodes != nullptr )
            xmlXPathFreeNodeSet(refineNodes);
        return false;
    }
    
    xmlXPathFreeNodeSet(metadataNodes);
    xmlXPathFreeNodeSet(refineNodes);
    
    // now any content type bindings
    xmlNodeSetPtr bindingNodes = nullptr;
    
    try
    {
        bindingNodes = xpath.Nodes("/opf:package/opf:bindings/*");
        if ( bindingNodes != nullptr )
        {
            for ( int i = 0; i < bindingNodes->nodeNr; i++ )
            {
                xmlNodePtr node = bindingNodes->nodeTab[i];
                if ( xmlStrcasecmp(node->name, MediaTypeElementName) != 0 )
                    continue;
                
                ////////////////////////////////////////////////////////////
                // ePub Publications 3.0 §3.4.16: The `mediaType` Element
                
                // The media-type attribute is required.
                string mediaType = _getProp(node, "media-type");
                if ( mediaType.empty() )
                {
                    HandleError(EPUBError::OPFBindingHandlerNoMediaType);
                    throw false;
                }
                
                // Each child mediaType of a bindings element must define a unique
                // content type in its media-type attribute, and the media type
                // specified must not be a Core Media Type.
                if ( _contentHandlers[mediaType].empty() == false )
                {
                    // user shouldn't have added manual things yet, but for safety we'll look anyway
                    for ( auto ptr : _contentHandlers[mediaType] )
                    {
                        if ( typeid(*ptr) == typeid(MediaHandler) )
                        {
                            HandleError(EPUBError::OPFMultipleBindingsForMediaType);
                        }
                    }
                }
                if ( CoreMediaTypes.find(mediaType) != CoreMediaTypes.end() )
                {
                    HandleError(EPUBError::OPFCoreMediaTypeBindingEncountered);
                }
                
                // The handler attribute is required
                string handlerID = _getProp(node, "handler");
                if ( handlerID.empty() )
                {
                    HandleError(EPUBError::OPFBindingHandlerNotFound);
                }
                
                // The required handler attribute must reference the ID [XML] of an
                // item in the manifest of the default implementation for this media
                // type. The referenced item must be an XHTML Content Document.
                ManifestItemPtr handlerItem = ManifestItemWithID(handlerID);
                if ( !handlerItem )
                {
                    HandleError(EPUBError::OPFBindingHandlerNotFound);
                }
                if ( handlerItem->MediaType() != "application/xhtml+xml" )
                {
                    
                    HandleError(EPUBError::OPFBindingHandlerInvalidType, _Str("Media handlers must be XHTML content documents, but referenced item has type '", handlerItem->MediaType(), "'."));
                }
                
                // All XHTML Content Documents designated as handlers must have the
                // `scripted` property set in their manifest item's `properties`
                // attribute.
                if ( handlerItem->HasProperty(ItemProperties::HasScriptedContent) == false )
                {
                    HandleError(EPUBError::OPFBindingHandlerNotScripted);
                }
                
                // all good-- install it now
                _contentHandlers[mediaType].push_back(std::make_shared<MediaHandler>(sharedMe, mediaType, handlerItem->AbsolutePath()));
            }
        }
    }
    catch (std::exception& exc)
    {
        std::cerr << "Exception processing OPF file: " << exc.what() << std::endl;
        if ( bindingNodes != nullptr )
            xmlXPathFreeNodeSet(bindingNodes);
        throw;
    }
    catch (...)
    {
        if ( bindingNodes != nullptr )
            xmlXPathFreeNodeSet(bindingNodes);
        return false;
    }
    
    xmlXPathFreeNodeSet(bindingNodes);
    
    // now the navigation tables
    for ( auto item : _manifest )
    {
        if ( !item.second->HasProperty(ItemProperties::Navigation) )
            continue;
        
        NavigationList tables = NavTablesFromManifestItem(sharedMe, item.second);
        for ( auto table : tables )
        {
            // have to dynamic_cast these guys to get the right pointer type
            shared_ptr<class NavigationTable> navTable = std::dynamic_pointer_cast<class NavigationTable>(table);
#if EPUB_HAVE(CXX_MAP_EMPLACE)
            _navigation.emplace(navTable->Type(), navTable);
#else
            _navigation[navTable->Type()] = navTable;
#endif
        }
    }
    
    // lastly, let's set the media support information
    InitMediaSupport();
    
    return true;
}
/**
* 初始化
* @param void
* @return void
*/
void CPointCodeList::OnInit()
{
	// 解析配置文件
	ParseXML();
}
예제 #28
0
파일: drivers.c 프로젝트: carriercomm/osx-2
static long
LoadDriverPList( char * dirSpec, char * name, long bundleType )
{
    long      length, driverPathLength;
    ModulePtr module;
    TagPtr    personalities;
    char *    buffer = 0;
    char *    tmpDriverPath = 0;
    long      ret = -1;

    do {
        // Save the driver path.
        
        sprintf(gFileSpec, "%s/%s/%s", dirSpec, name,
                (bundleType == kCFBundleType2) ? "Contents/MacOS/" : "");
        driverPathLength = strlen(gFileSpec) + 1;

        tmpDriverPath = malloc(driverPathLength);
        if (tmpDriverPath == 0) break;

        strcpy(tmpDriverPath, gFileSpec);
  
        // Construct the file spec to the plist, then load it.

        sprintf(gFileSpec, "%s/%s/%sInfo.plist", dirSpec, name,
                (bundleType == kCFBundleType2) ? "Contents/" : "");

        length = LoadFile(gFileSpec);
        if (length == -1) break;

        length = length + 1;
        buffer = malloc(length);
        if (buffer == 0) break;

        strlcpy(buffer, (char *)kLoadAddr, length);

        // Parse the plist.

        ret = ParseXML(buffer, &module, &personalities);
        if (ret != 0) { break; }

        // Allocate memory for the driver path and the plist.

        module->driverPath = tmpDriverPath;
        module->plistAddr = (void *)malloc(length);
  
        if ((module->driverPath == 0) || (module->plistAddr == 0))
            break;

        // Save the driver path in the module.
        //strcpy(module->driverPath, tmpDriverPath);
        tmpDriverPath = 0;

        // Add the plist to the module.

        strlcpy(module->plistAddr, (char *)kLoadAddr, length);
        module->plistLength = length;
  
        // Add the module to the end of the module list.
        
        if (gModuleHead == 0)
            gModuleHead = module;
        else
            gModuleTail->nextModule = module;
        gModuleTail = module;
  
        // Add the persionalities to the personality list.
    
        if (personalities) personalities = personalities->tag;
        while (personalities != 0)
        {
            if (gPersonalityHead == 0)
                gPersonalityHead = personalities->tag;
            else
                gPersonalityTail->tagNext = personalities->tag;
            
            gPersonalityTail = personalities->tag;
            personalities = personalities->tagNext;
        }
        
        ret = 0;
    }
    while (0);
    
    if ( buffer )        free( buffer );
    if ( tmpDriverPath ) free( tmpDriverPath );

    return ret;
}
예제 #29
0
int main(int argc, char **argv)
{
	FILE *fpin;
	AppData *ad;

	if (argc < 2 || argc > 4)
	{
		fprintf(stderr, "gpxrewrite - Part of %s\n", PACKAGE_STRING);
		fprintf(stderr, "Error:  Incorrect arguments\n");
		fprintf(stderr, "    gpxrewrite settings.ini   (reads file from stdin, writes to stdout)\n");
		fprintf(stderr, "    gpxrewrite settings.ini gpxfile.gpx   (writes to stdout)\n");
		fprintf(stderr, "    gpxrewrite settings.ini gpxfile.gpx output.gpx\n");
		exit(1);
	}

	DEBUG("Get memory");
	ad = getMemory(sizeof(AppData));
	DEBUG("Write default settings");
	WriteDefaultSettings(&(ad->settings));
	DEBUG("Read settings file");
	ReadSettings(&(ad->settings), argv[1]);

	if (argc >= 3)
	{
		DEBUG("Opening input file");
		fpin = fopen(argv[2], "r");
		if (! fpin)
		{
			fprintf(stderr, "Error opening input file: %s\n", argv[2]);
			exit(3);
		}
	}
	else
	{
		DEBUG("Using stdin");
		fpin = stdin;
	}

	if (argc >= 4)
	{
		DEBUG("Opening output file");
		ad->fpout = fopen(argv[3], "w");
		if (! ad->fpout)
		{
			fprintf(stderr, "Error opening output file: %s\n", argv[3]);
			exit(4);
		}
	}
	else
	{
		DEBUG("Using stdout");
		ad->fpout = stdout;
	}

	DEBUG("Writing XML header");
	fputs("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", ad->fpout);
	DEBUG("Parsing XML");
	ParseXML(fpin, &WaypointHandler, &NonWaypointHandler, (void *) ad);
	DEBUG("Writing trailing newline");
	fputs(GetXMLNewline(), ad->fpout);

	if (fpin != stdin)
	{
		DEBUG("Closing input file");
		fclose(fpin);
	}

	if (ad->fpout != stdout)
	{
		DEBUG("Closing output file");
		fclose(ad->fpout);
	}

	DEBUG("Freeing settings");
	FreeSettings(&(ad->settings));
	DEBUG("Freeing memory");
	freeMemory((void **) &ad);

	return 0;
}
/**
* 重新加载
* @param void
* @return void
*/
void CPointCodeList::OnReload(void)
{
	m_uiCountAll = 0;	// 点代码总数
	m_olsPointCode.RemoveAll();	// 移除队列
	ParseXML();	// 解析配置文件
}