HRESULT XMLFile::LoadFromFile(CString fn)
	{
		root->Clear();

		CComPtr<IXmlReader>		reader;
		CComPtr<IStream>		stream;
		HRESULT					hr = NOERROR;

		do {
			// create file stream
			hr = SHCreateStreamOnFile(fn, STGM_READ | STGM_SHARE_DENY_WRITE, &stream);
			if (FAILED(hr)) 
				break;

			// reader
			hr = CreateXmlReader(IID_IXmlReader, (void**)&reader, NULL);
			if (FAILED(hr)) 
				break;

			// select input
			hr = reader->SetInput(stream);
			if (FAILED(hr)) 
				break;

			int ret = LoadFromXmlReader(reader);
			if (ret < 0) {
				hr = ret;
			} else {
				hr = NOERROR;
			}
		} while (0);

		return hr;
	}	
Beispiel #2
0
Node *
ReadFile
(
   const char * fileName
)
{
   IStream * pStream;
   IXmlReader * pReader;

   HANDLE fileHandle = CreateFile(fileName, FILE_GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
   if (fileHandle == INVALID_HANDLE_VALUE)
   {
      Fatal("Cannot open XML file %s", fileName);
   }

   if (FAILED(CreateStreamOnHandle(fileHandle, &pStream)))
   {
      Fatal("Cannot create stream from file");
   }

   if (FAILED(CreateXmlReader(__uuidof(IXmlReader), (void**) &pReader, nullptr)))
   {
      Fatal("Cannot create XML reader");
   }

   if (FAILED(pReader->SetProperty(XmlReaderProperty_DtdProcessing, DtdProcessing_Prohibit)))
   {
      Fatal("Cannot prohibit DTD processing");
   }

   if (FAILED(pReader->SetInput(pStream)))
   {
      Fatal("Cannot set XML reader input");
   }

   Node * topNode;
   if (FAILED(ParseXml(pReader, &topNode)))
   {
      unsigned int line, linePos;
      pReader->GetLineNumber(&line);
      pReader->GetLinePosition(&linePos);
      fprintf(
         stderr,
         "Error on line %d, position %d in \"%s\".\n",
         line,
         linePos,
         fileName);
      Fatal("Error parsing XML");
   }

   SAFERELEASE(pReader);
   SAFERELEASE(pStream);
   CloseHandle(fileHandle);

   return topNode;
}
HRESULT CreateStreamReader(LPCWSTR path, IXmlReader **ppReader, IStream **ppFileStream)
{
	HRESULT hr = S_FALSE;

	if(ppReader != NULL && ppFileStream != NULL)
	{
		hr = CreateXmlReader(IID_PPV_ARGS(ppReader), NULL);
		EXIT_NOT_S_OK(hr);

		hr = SHCreateStreamOnFileW(path, STGM_READ, ppFileStream);
		EXIT_NOT_S_OK(hr);

		hr = (*ppReader)->SetInput(*ppFileStream);
		EXIT_NOT_S_OK(hr);
	}

NOT_S_OK:
	return hr;
}
Beispiel #4
0
bool Utils::xmlopen(IStream **pFileStream, IXmlReader **pReader,WCHAR* filename) {
	HRESULT hr;

	if (FAILED(hr = SHCreateStreamOnFile(filename, STGM_READ, &(*pFileStream)))) {
      wprintf(L"Error creating file reader, error is %08.8lx", hr);
      return false;
   }

   if (FAILED(hr = CreateXmlReader(__uuidof(IXmlReader), (void**) pReader, NULL))) {
      wprintf(L"Error creating xml reader, error is %08.8lx", hr);
      return false;
   }

   if (FAILED(hr = (*pReader)->SetProperty(XmlReaderProperty_DtdProcessing, DtdProcessing_Prohibit))) {
      wprintf(L"Error setting XmlReaderProperty_DtdProcessing, error is %08.8lx", hr);
      return false;
   }

   if (FAILED(hr = (*pReader)->SetInput(*pFileStream))) {
      wprintf(L"Error setting input for reader, error is %08.8lx", hr);
      return false;
   }
   return true;
}
int _tmain(int argc, WCHAR* argv[])
{
    HRESULT hr;
    CComPtr<IStream> pFileStream;
    CComPtr<IXmlReader> pReader;
    CComPtr<IXmlReaderInput> pReaderInput;
    XmlNodeType nodetype;
    const WCHAR* pwszPrefix;
    const WCHAR* pwszLocalName;
    const WCHAR* pwszValue;
    UINT cwchPrefix;

    if (argc != 2)
    {
        wprintf(L"Usage: XmlLiteReadWithEncoding.exe name-of-input-file\n");
        return 0;
    }

    // Open read-only input stream
    if (FAILED(hr = FileStream::OpenFile(argv[1], &pFileStream, FALSE)))
    {
        wprintf(L"Error creating file reader, error is %08.8lx", hr);
        return -1;
    }

    if (FAILED(hr = CreateXmlReader(__uuidof(IXmlReader),(void**) &pReader, NULL)))
    {
        wprintf(L"Error creating xml reader, error is %08.8lx", hr);
        return -1;
    }

    if (FAILED(hr = CreateXmlReaderInputWithEncodingName(pFileStream, NULL, L"utf-16", FALSE,
        L"c:\temp", &pReaderInput)))
    {
        wprintf(L"Error creating xml reader with encoding code page, error is %08.8lx", hr);
        return -1;
    }

    if (FAILED(hr = pReader->SetInput(pReaderInput)))
    {
        wprintf(L"Error setting input for reader, error is %08.8lx", hr);
        return -1;
    }

    while (TRUE)
    {
        hr = pReader->Read(&nodetype);
        if (S_FALSE == hr)
            break;
        if (S_OK != hr)
        {
            wprintf(L"\nXmlLite Error: %08.8lx\n", hr);
            return -1;
        }
        switch (nodetype)
        {
        case XmlNodeType_XmlDeclaration:
            wprintf(L"<?xml ");
            if (FAILED(hr = WriteAttributes(pReader)))
            {
                wprintf(L"Error, Method: WriteAttributes, error is %08.8lx", hr);
                return -1;
            }
            wprintf(L"?>\r\n");
            break;
        case XmlNodeType_Element:
            if (FAILED(hr = pReader->GetPrefix(&pwszPrefix, &cwchPrefix)))
            {
                wprintf(L"Error, Method: GetPrefix, error is %08.8lx", hr);
                return -1;
            }
            if (FAILED(hr = pReader->GetLocalName(&pwszLocalName, NULL)))
            {
                wprintf(L"Error, Method: GetLocalName, error is %08.8lx", hr);
                return -1;
            }
            if (cwchPrefix > 0)
                wprintf(L"<%s:%s ", pwszPrefix, pwszLocalName);
            else
                wprintf(L"<%s ", pwszLocalName);

            if (FAILED(hr = WriteAttributes(pReader)))
            {
                wprintf(L"Error, Method: WriteAttributes, error is %08.8lx", hr);
                return -1;
            }

            if (pReader->IsEmptyElement() )
                wprintf(L"/>");
            else
                wprintf(L">");
            break;
        case XmlNodeType_EndElement:
            if (FAILED(hr = pReader->GetPrefix(&pwszPrefix, &cwchPrefix)))
            {
                wprintf(L"Error, Method: GetPrefix, error is %08.8lx", hr);
                return -1;
            }
            if (FAILED(hr = pReader->GetLocalName(&pwszLocalName, NULL)))
            {
                wprintf(L"Error, Method: GetLocalName, error is %08.8lx", hr);
                return -1;
            }
            if (cwchPrefix > 0)
                wprintf(L"</%s:%s>", pwszPrefix, pwszLocalName);
            else
                wprintf(L"</%s>", pwszLocalName);
            break;
        case XmlNodeType_Text:
        case XmlNodeType_Whitespace:
            if (FAILED(hr = pReader->GetValue(&pwszValue, NULL)))
            {
                wprintf(L"Error, Method: GetValue, error is %08.8lx", hr);
                return -1;
            }
            wprintf(L"%s", pwszValue);
            break;
        case XmlNodeType_CDATA:
            if (FAILED(hr = pReader->GetValue(&pwszValue, NULL)))
            {
                wprintf(L"Error, Method: GetValue, error is %08.8lx", hr);
                return -1;
            }
            wprintf(L"<![CDATA[%s]]>", pwszValue);
            break;
        case XmlNodeType_ProcessingInstruction:
            if (FAILED(hr = pReader->GetValue(&pwszValue, NULL)))
            {
                wprintf(L"Error, Method: GetValue, error is %08.8lx", hr);
                return -1;
            }
            wprintf(L"<?%s?>", pwszValue);
            break;
        case XmlNodeType_Comment:
            if (FAILED(hr = pReader->GetValue(&pwszValue, NULL)))
            {
                wprintf(L"Error, Method: GetValue, error is %08.8lx", hr);
                return -1;
            }
            wprintf(L"<!--%s-->", pwszValue);
            break;
        case XmlNodeType_DocumentType:
            wprintf(L"<!-- DOCTYPE is not printed -->\r\n");
            break;
        }
    }
    wprintf(L"\n");
    return 0;
}
int _tmain(int argc, WCHAR* argv[])
{
    HRESULT hr;
    CComPtr<IStream> pFileStream;
    CComPtr<IStream> pOutFileStream;
    CComPtr<IXmlReader> pReader;
    CComPtr<IXmlWriter> pWriter;
    CComPtr<IXmlReaderInput> pReaderInput;
    CComPtr<IXmlWriterOutput> pWriterOutput;

    if (argc != 3)
    {
        wprintf( L"Usage: XmlReaderWriter.exe name-of-input-file name-of-output-file\n");
        return 0;
    }

    //Open read-only input stream
    if (FAILED(hr = FileStream::OpenFile(argv[1], &pFileStream, FALSE)))
    {
        wprintf(L"Error creating file reader, error is %08.8lx", hr);
        return -1;
    }

    //Open writeable output stream
    if (FAILED(hr = FileStream::OpenFile(argv[2], &pOutFileStream, TRUE)))
    {
        wprintf(L"Error creating file writer, error is %08.8lx", hr);
        return -1;
    }

    if (FAILED(hr = CreateXmlReader(__uuidof(IXmlReader), (void**) &pReader, NULL)))
    {
        wprintf(L"Error creating xml reader, error is %08.8lx", hr);
        return -1;
    }

    pReader->SetProperty(XmlReaderProperty_DtdProcessing, DtdProcessing_Prohibit);

    if (FAILED(hr = CreateXmlReaderInputWithEncodingCodePage(pFileStream, NULL, 65001, FALSE,
                                                             L"c:\temp", &pReaderInput)))
    {
        wprintf(L"Error creating xml reader with encoding code page, error is %08.8lx", hr);
        return -1;
    }

    if (FAILED(hr = CreateXmlWriter(__uuidof(IXmlWriter),(void**) &pWriter, NULL)))
    {
        wprintf(L"Error creating xml writer, error is %08.8lx", hr);
        return -1;
    }

    if (FAILED(hr = CreateXmlWriterOutputWithEncodingCodePage(pOutFileStream, NULL, 65001,
                                                              &pWriterOutput)))
    {
        wprintf(L"Error creating xml reader with encoding code page, error is %08.8lx", hr);
        return -1;
    }

    if (FAILED(hr = pReader->SetInput(pReaderInput)))
    {
        wprintf(L"Error setting input for reader, error is %08.8lx", hr);
        return -1;
    }

    if (FAILED(hr = pWriter->SetOutput(pWriterOutput)))
    {
        wprintf(L"Error setting output for writer, error is %08.8lx", hr);
        return -1;
    }

    if (FAILED(hr = pWriter->SetProperty(XmlWriterProperty_Indent, TRUE)))
    {
        wprintf(L"Error setting indent property in writer, error is %08.8lx", hr);
        return -1;
    }

    XmlNodeType nodeType;
    const WCHAR* pQName;
    const WCHAR* pValue;
    double originalPrice = 0.0;
    double newPrice = 0.0;
    WCHAR priceString[100];
    bool inPrice = FALSE;

    /*
     * This quick start reads an XML of the form
     * <books>
     *   <book name="name of book1">
     *    <price>price-of-book1</price>
     *   </book>
     *   <book name="name of book2">
     *    <price>price-of-book2</price>
     *   </book>
     *  </books>
     *
     * and applies a 25% discount to the price of the book. It also adds originalPrice and discount
     * as two attributes to the element price. If the price is empty or an empty element, it does
     * not make any changes. So the transformed XML will be:
     *
     * <books>
     *   <book name="name of book1">
     *    <price originalPrice="price-of-book1" discount="25%">
     *           discounted-price-of-book1
     *       </price>
     *   </book>
     *   <book name="name of book2">
     *    <price originalPrice="price-of-book2" discount="25%">
     *           discounted-price-of-book2
     *       </price>
     *   </book>
     *  </books>
     *
     */

    //read until there are no more nodes
    while (S_OK == (hr = pReader->Read(&nodeType)))
    {

        // WriteNode will move the reader to the next node, so inside the While Read loop, it is
        // essential that we use WriteNodeShallow, which will not move the reader. 
        // If not, a node will be skipped every time you use WriteNode in the while loop.

        switch (nodeType)
        {
        case XmlNodeType_Element:
            {
                if (pReader->IsEmptyElement())
                {
                    if (FAILED(hr = pWriter->WriteNodeShallow(pReader, FALSE)))
                    {
                        wprintf(L"Error writing WriteNodeShallow, error is %08.8lx", hr);
                        return -1;
                    }
                }
                else
                {
                    // if you are not interested in the length it may be faster to use 
                    // NULL for the length parameter
                    if (FAILED(hr = pReader->GetQualifiedName(&pQName, NULL)))
                    {
                        wprintf(L"Error reading element name, error is %08.8lx", hr);
                        return -1;
                    }
                    
                    //if the element is price, then discount price by 25%   
                    if (wcscmp(pQName, L"price") == 0)
                    {
                        inPrice = TRUE;
                        if (FAILED(hr = pWriter->WriteNodeShallow(pReader, FALSE)))
                        {
                            wprintf(L"Error writing WriteNodeShallow, error is %08.8lx", hr);
                            return -1;
                        }


                    }
                    else
                    {
                        inPrice = FALSE;
                        if (FAILED(hr = pWriter->WriteNodeShallow(pReader, FALSE)))
                        {
                            wprintf(L"Error writing WriteNodeShallow, error is %08.8lx", hr);
                            return -1;
                        }

                    }
                }
            }
            break;
        case XmlNodeType_Text:
            if (inPrice == TRUE)
            {
                if (FAILED(hr = pReader->GetValue(&pValue, NULL)))
                {
                    wprintf(L"Error reading value, error is %08.8lx", hr);
                    return -1;
                }
                
                //apply discount to the node
                originalPrice = _wtof(pValue);
                newPrice = originalPrice * 0.75;

                if (FAILED(hr = StringCbPrintfW(priceString, sizeof (priceString), L"%f",
                                                newPrice)))
                {
                    wprintf(L"Error using StringCchPrintfW, error is %08.8lx", hr);
                    return -1;
                }

                //write attributes if any
                if (FAILED(hr = pWriter->WriteAttributeString(NULL, L"originalPrice", NULL,
                                                              pValue)))
                {
                    wprintf(L"Error writing WriteAttributeString, error is %08.8lx", hr);
                    return -1;
                }

                if (FAILED(hr = pWriter->WriteAttributeString(NULL, L"discount", NULL, L"25%")))
                {
                    wprintf(L"Error writing WriteAttributeString, error is %08.8lx", hr);
                    return -1;
                }
                if (FAILED(hr = pWriter->WriteString(priceString)))
                {
                    wprintf(L"Error writing WriteString, error is %08.8lx", hr);
                    return -1;
                }
                inPrice = FALSE;
            }
            else
            {
                if (FAILED(hr = pWriter->WriteNodeShallow(pReader, FALSE)))
                {
                    wprintf(L"Error writing WriteNodeShallow, error is %08.8lx", hr);
                    return -1;
                }
            }

            break;
        case XmlNodeType_EndElement:
            if (FAILED(hr = pReader->GetQualifiedName(&pQName, NULL)))
            {
                wprintf(L"Error reading element name, error is %08.8lx", hr);
                return -1;
            }
            
            if (wcscmp(pQName, L"price") == 0)  //if the end element is price, then reset inPrice
                inPrice = FALSE;
            
            if (FAILED(hr = pWriter->WriteFullEndElement()))
            {
                wprintf(L"Error writing WriteFullEndElement, error is %08.8lx", hr);
                return -1;
            }
            break;
        default:
            {
                if (FAILED(hr = pWriter->WriteNodeShallow(pReader, FALSE)))
                {
                    wprintf(L"Error writing WriteNodeShallow, error is %08.8lx", hr);
                    return -1;
                }
            }
            break;
        }

    }
    return 0;
}
int _tmain(int argc, WCHAR* argv[])
{
    HRESULT hr;
    CComPtr<IStream> pFileStream;
    CComPtr<IXmlReader> pReader;
    XmlNodeType nodetype;
    const WCHAR* pwszPrefix;
    const WCHAR* pwszLocalName;
    const WCHAR* pwszNamespaceUri;
    UINT cwchPrefix;

    if (argc != 2)
    {
        wprintf(L"Usage: XmlLiteNamespaceReader.exe name-of-input-file\n");
        return 0;
    }

    //Open read-only input stream
    if (FAILED(hr = FileStream::OpenFile(argv[1], &pFileStream, FALSE)))
    {
        wprintf(L"Error creating file reader, error is %08.8lx", hr);
        return -1;
    }

    if (FAILED(hr = CreateXmlReader(__uuidof(IXmlReader), (void**) &pReader, NULL)))
    {
        wprintf(L"Error creating xml reader, error is %08.8lx", hr);
        return -1;
    }

    if (FAILED(hr = pReader->SetInput(pFileStream)))
    {
        wprintf(L"Error setting input for reader, error is %08.8lx", hr);
        return -1;
    }

    while (true)
    {
        hr = pReader->Read(&nodetype);
        if (S_FALSE == hr)
            break;
        if (S_OK != hr)
        {
            wprintf(L"\nXmlLite Error: %08.8lx\n", hr);
            return -1;
        }
        switch (nodetype)
        {
        case XmlNodeType_Element:
            if (FAILED(hr = pReader->GetPrefix(&pwszPrefix, &cwchPrefix)))
            {
                wprintf(L"Error, Method: GetPrefix, error is %08.8lx", hr);
                return -1;
            }
            if (FAILED(hr = pReader->GetLocalName(&pwszLocalName, NULL)))
            {
                wprintf(L"Error, Method: GetLocalName, error is %08.8lx", hr);
                return -1;
            }
            if (cwchPrefix > 0)
                wprintf(L"%s:%s ", pwszPrefix, pwszLocalName);
            else
                wprintf(L"%s ", pwszLocalName);
            if (FAILED(hr = pReader->GetNamespaceUri(&pwszNamespaceUri, NULL)))
            {
                wprintf(L"Error, Method: GetNamespaceUri, error is %08.8lx", hr);
                return -1;
            }
            wprintf(L"Namespace=%s\n", pwszNamespaceUri);

            if (FAILED(hr = WriteAttributes(pReader)))
            {
                wprintf(L"Error, Method: WriteAttributes, error is %08.8lx", hr);
                return -1;
            }
            break;
        }
    }

    wprintf(L"\n");
    return 0;
}
Beispiel #8
0
int Quiz::inputQuiz(int x){
	HRESULT hr;
   CComPtr<IStream> pFileStream;
   CComPtr<IXmlReader> pReader;
   XmlNodeType nodeType;
   //const WCHAR* pwszPrefix;
   const WCHAR* pwszLocalName;
   const WCHAR* pwszValue;
   //UINT cwchPrefix;

   if (FAILED(hr = SHCreateStreamOnFile(L"file.xml", STGM_READ, &pFileStream))) {
      wprintf(L"Error creating file reader, error is %08.8lx", hr);
	   getchar();
      return -1;
   }

   if (FAILED(hr = CreateXmlReader(__uuidof(IXmlReader), (void**) &pReader, NULL))) {
      wprintf(L"Error creating xml reader, error is %08.8lx", hr);
      return -1;
   }

   if (FAILED(hr = pReader->SetProperty(XmlReaderProperty_DtdProcessing, DtdProcessing_Prohibit))) {
      wprintf(L"Error setting XmlReaderProperty_DtdProcessing, error is %08.8lx", hr);
      return -1;
   }

   if (FAILED(hr = pReader->SetInput(pFileStream))) {
      wprintf(L"Error setting input for reader, error is %08.8lx", hr);
      return -1;
   }

   int i = 0;
   while (S_OK == (hr = pReader->Read(&nodeType))) {
	   if (nodeType == XmlNodeType_Element) {
		   if (FAILED(hr = pReader->GetLocalName(&pwszLocalName, NULL))) {
            wprintf(L"Error getting local name, error is %08.8lx", hr);
            return -1;
		   }
		   if (wcscmp(pwszLocalName,L"entry") == 0) i++; // i la` so element trong xml
	   }
   }

   LARGE_INTEGER liBeggining = { 0 };
   pFileStream->Seek(liBeggining, STREAM_SEEK_SET, NULL);
   pReader->SetInput(pFileStream);

   int k=0,j=1;//k la` bien dem'. j bien' de? lay ra phan` tu? thu' j. j = 1 thi` lay' phan` tu? dau` tien
   
   while (S_OK == (hr = pReader->Read(&nodeType))) {
      switch (nodeType) {

      case XmlNodeType_Element: 
         if (FAILED(hr = pReader->GetLocalName(&pwszLocalName, NULL))) {
            wprintf(L"Error getting local name, error is %08.8lx", hr);
            return -1;
         }
		 if (wcscmp(pwszLocalName,L"entry") == 0) k++;

         if (FAILED(hr = pReader->MoveToElement())) {
            wprintf(L"Error moving to the element that owns the current attribute node, error is %08.8lx", hr);
            return -1;
         }
         if (pReader->IsEmptyElement() )
            wprintf(L" (empty element)\n");
         break;
      case XmlNodeType_EndElement:
          if (FAILED(hr = pReader->GetLocalName(&pwszLocalName, NULL))) {
            wprintf(L"Error getting local name, error is %08.8lx", hr);
            return -1;
         }
         break;

      case XmlNodeType_Text:

      case XmlNodeType_CDATA:
         if (FAILED(hr = pReader->GetValue(&pwszValue, NULL))) {
            wprintf(L"Error getting value, error is %08.8lx", hr);
            return -1;
         }
		 if (wcscmp(pwszLocalName,L"Question") == 0) {
			 setQuestion(strdup(narrow(pwszValue).c_str()));
		 }
		 else if (wcscmp(pwszLocalName,L"Answer") == 0) {
			 setAnswer(strdup(narrow(pwszValue).c_str()));
		 }
         break;

      case XmlNodeType_ProcessingInstruction:
         if (FAILED(hr = pReader->GetLocalName(&pwszLocalName, NULL))) {
            wprintf(L"Error getting name, error is %08.8lx", hr);
            return -1;
         }
         if (FAILED(hr = pReader->GetValue(&pwszValue, NULL))) {
            wprintf(L"Error getting value, error is %08.8lx", hr);
            return -1;
         }
         wprintf(L"Processing Instruction name:%S value:%S\n", pwszLocalName, pwszValue);
         break;

      case XmlNodeType_Comment:
         if (FAILED(hr = pReader->GetValue(&pwszValue, NULL))) {
            wprintf(L"Error getting value, error is %08.8lx", hr);
            return -1;
         }
         wprintf(L"Comment: %s\n", pwszValue);
         break;

      case XmlNodeType_DocumentType:
         wprintf(L"DOCTYPE is not printed\n");
         break;
      }
	  if (k > j) break;
   }
   return 0;
}
BOOL DataRecordsXmlSerializer::Import(LPCTSTR fileName, FullTrackRecordCollection& col)
{
	HRESULT hr;
	CComPtr<IStream> pInFileStream;
	CComPtr<IXmlReader> pReader;

	//Open writeable output stream
	if (FAILED(hr = FileStream::OpenFile(fileName, &pInFileStream, FALSE)))
	{
		TRACE(_T("@1 DataRecordsXmlSerializer::Import. Error creating file reader, error is %08.8lx"), hr);
		return FALSE;
	}

	if (FAILED(hr = CreateXmlReader(__uuidof(IXmlReader),(void**) &pReader, NULL)))
	{
		TRACE(_T("@1 DataRecordsXmlSerializer::Import. Error creating IXmlReader, error is %08.8lx"), hr);
		return FALSE;
	}

	if (FAILED(hr = pReader->SetInput(pInFileStream)))
	{
		TRACE(_T("@1 DataRecordsXmlSerializer::Import. Error setting Input for reader, error is %08.8lx"), hr);
		return FALSE;
	}
	XmlLiteReaderHelper hlp(*pReader);
	if (hlp.FindElement(_T("fulltrackcollection"), 0))
	{
		while (hlp.FindElement(_T("fulltrackrecord"), 1))
		{
			FullTrackRecord* pRec = new FullTrackRecord;
			XmlNodeType nodeType;
			const WCHAR* pwszLocalName = NULL;
			while (pReader->Read(&nodeType) == S_OK)
			{
				if (nodeType == XmlNodeType_Element)
				{
					if (pReader->GetLocalName(&pwszLocalName, NULL) == S_OK)
					{
						if (_tcsicmp(pwszLocalName, _T("trackname")) == 0)
							pRec->track.name = hlp.GetElementText();
						//else if (_tcsicmp(pwszLocalName, _T("trackdateadded")) == 0)
						//	pRec->track.dateAdded = hlp.GetElementText();
						else if (_tcsicmp(pwszLocalName, _T("tracklocation")) == 0)
							pRec->track.location = hlp.GetElementText();
						else if (_tcsicmp(pwszLocalName, _T("trackbitrate")) == 0)
							pRec->track.bitrate = _ttoi(hlp.GetElementText());
						else if (_tcsicmp(pwszLocalName, _T("trackduration")) == 0)
							pRec->track.duration = _ttoi(hlp.GetElementText());
						else if (_tcsicmp(pwszLocalName, _T("tracksize")) == 0)
							pRec->track.size = _ttoi(hlp.GetElementText());
						else if (_tcsicmp(pwszLocalName, _T("tracktrackNo")) == 0)
							pRec->track.trackNo = _ttoi(hlp.GetElementText());
						else if (_tcsicmp(pwszLocalName, _T("trackyear")) == 0)
							pRec->track.year = _ttoi(hlp.GetElementText());
						else if (_tcsicmp(pwszLocalName, _T("trackrating")) == 0)
							pRec->track.rating = _ttoi(hlp.GetElementText());
						else if (_tcsicmp(pwszLocalName, _T("albumname")) == 0)
							pRec->album.name = hlp.GetElementText();
						else if (_tcsicmp(pwszLocalName, _T("albumrating")) == 0)
							pRec->album.rating = _ttoi(hlp.GetElementText());
						else if (_tcsicmp(pwszLocalName, _T("albumyear")) == 0)
							pRec->album.year = _ttoi(hlp.GetElementText());
						else if (_tcsicmp(pwszLocalName, _T("artistname")) == 0)
							pRec->artist.name = hlp.GetElementText();
						else if (_tcsicmp(pwszLocalName, _T("artistrating")) == 0)
							pRec->artist.rating = _ttoi(hlp.GetElementText());
						else if (_tcsicmp(pwszLocalName, _T("genrename")) == 0)
							pRec->genre.name = hlp.GetElementText();

					}
				}
				else if (nodeType == XmlNodeType_EndElement)
				{
					UINT depth = 0;
					pReader->GetDepth(&depth);
					if (depth < 3)
						break;
				}
			}
			col.push_back(FullTrackRecordSP(pRec));
		}
	}
	pReader.Release();
	pInFileStream.Release();
	return TRUE;
}
int _tmain(int argc, WCHAR* argv[])
{
    HRESULT hr;
    CComPtr<IStream> pFileStream;
    CComPtr<IXmlReader> pReader;
    XmlNodeType nodetype;

    if (argc != 2)
    {
        wprintf(L"Usage: XmlLiteChunkReader.exe name-of-input-file\n");
        return 0;
    }
    
    //Open read-only input stream
    if (FAILED(hr = FileStream::OpenFile(argv[1], &pFileStream, FALSE)))
    {
        wprintf(L"Error creating file   reader, error is %08.8lx", hr);
        return -1;
    }

    if (FAILED(hr = CreateXmlReader(__uuidof(IXmlReader), (void**) &pReader, NULL)))
    {
        wprintf(L"Error creating xml reader, error is %08.8lx", hr);
        return -1;
    }

    if (FAILED(hr = pReader->SetInput(pFileStream)))
    {
        wprintf(L"Error setting input for reader, error is %08.8lx", hr);
        return -1;
    }

    while (TRUE)
    {
        hr = pReader->Read(&nodetype);
        if (S_FALSE == hr)
            break;
        if (S_OK != hr)
        {
            wprintf(L"\nXmlLite Error: %08.8lx\n", hr);
            return -1;
        }
        switch (nodetype)
        {
        case XmlNodeType_Element:
            if (FAILED(hr = WriteAttributes(pReader)))
            {
                wprintf(L"Error, Method: WriteAttributes, error is %08.8lx", hr);
                return -1;
            }
            break;
        case XmlNodeType_Text:
        case XmlNodeType_Whitespace:
            const UINT buffSize = 24;
            WCHAR buff[buffSize];
            UINT charsRead;

            while (TRUE)
            {
                hr = pReader->ReadValueChunk(buff, buffSize - 1, &charsRead);
                if (S_FALSE == hr || 0 == charsRead)
                    break;
                if (S_OK != hr)
                {
                    wprintf(L"\nXmlLite Error: %08.8lx\n", hr);
                    return -1;
                }
                buff[charsRead] = L'\0';
                dotWhiteSpace(buff, charsRead);
                wprintf(L"element chunk size:%d >%s<\n", charsRead, buff);
            }
            break;
        }
    }
    wprintf(L"\n");
    return 0;
}
Beispiel #11
0
bool SFXmlReader::initFrameByXsd(string xsdPath)
{
	HRESULT hr = S_OK;
	CComPtr<IStream> pFileStream;
	CComPtr<IXmlReader> pReader;
	XmlNodeType nodeType = XmlNodeType_None;
	LPCWSTR nodeName;
	LPCWSTR name;
	LPCWSTR value;
	bool ret;

	//Open read-only input stream
	hr = SHCreateStreamOnFileA(xsdPath.c_str(), STGM_READ, &pFileStream);
	if (SUCCEEDED(hr))
	{
		hr = CreateXmlReader(__uuidof(IXmlReader), (void**)&pReader, NULL);
	}
	else
	{
		sf_cout(DEBUG_COM, "Error: Can't find the XSD file. (\"" << xsdPath << "\")" << endl);

		return false;
	}
	pReader->SetInput(pFileStream);
	hr = pReader->Read(NULL);

	UINT tabs = 0;
	vector<string> arrNodeBuffer;
	for (; S_OK == hr; hr = pReader->Read(NULL))
	{
		pReader->GetLocalName(&nodeName, NULL);
		if (nodeName[0] > L' ')
		{
			if (wcscmp(nodeName, L"element") == 0 || wcscmp(nodeName, L"attribute") == 0)
			{
				pReader->GetNodeType(&nodeType);
				if (nodeType == XmlNodeType_Element)
				{
					sf_wcout(DEBUG_RES_LOAD, endl);
					for (UINT i = 0; i < tabs; i++)
					{
						sf_wcout(DEBUG_RES_LOAD, L"\t");
					}
					sf_wcout(DEBUG_RES_LOAD, nodeName << L" ");

					POLL_XML_ATTR_BEGIN
						if (wcscmp(nodeName, L"element") == 0)
						{
							if (tabs >= arrNodeBuffer.size())
							{
								arrNodeBuffer.insert(arrNodeBuffer.end(), utfValue);
							}
							if (utfName == "name" || utfName == "ref")
							{
								arrNodeBuffer[tabs] = utfValue;
								if (m_frame.find(utfValue) == m_frame.end())
								{
									m_frame[utfValue].m_name = utfValue;
									m_frame[utfValue].m_index = 0;
									m_frame[utfValue].m_depth = 0;
									m_frame[utfValue].m_isOnly = true;
									m_frame[utfValue].m_parent = NULL;
									m_frame[utfValue].m_attrData = map<string, XsdAttrData>{};
									m_frame[utfValue].m_nodeData = {};
								}
								if (tabs > 0)
								{
									string parent = arrNodeBuffer[tabs - 1];

									m_frame[utfValue].m_parent = &m_frame[parent];
									m_frame[parent].m_nodeData.insert(m_frame[parent].m_nodeData.end(), &m_frame[utfValue]);
								}
								if (m_pFrameRootNode == NULL)
								{
									m_pFrameRootNode = &m_frame[utfValue];
								}
							}
							else if (utfName == "maxOccurs")
							{
								if (utfValue == "unbounded")
								{
									m_frame[arrNodeBuffer[tabs]].m_isOnly = false;
								}
							}
						}
						else if (wcscmp(nodeName, L"attribute") == 0)
						{
							if (utfName == "name")
							{
								map<string, XsdAttrData>& mapAttr = m_frame[arrNodeBuffer[tabs - 1]].m_attrData;

								mapAttr[utfName].m_name = utfValue;
								mapAttr[utfName].m_index = mapAttr.size();
							}
						}
					POLL_XML_ATTR_END
					if (!(pReader->IsEmptyElement()) && wcscmp(nodeName, L"element") == 0)
					{
						tabs++;
					}
				}
				else if (nodeType == XmlNodeType_EndElement)
				{
					tabs--;
				}
			}
/*
Modify this to avoid temp file I/O
*/
bool CXMLParser::extractData( wstring filename)
{
    bool bRet = false;
    HRESULT hr = S_OK;
    IXmlReader *pReader = nullptr;
    IStream *pStream = nullptr;
    XmlNodeType nodeType;
    const TCHAR* pwszName;
    const TCHAR* pwszValue;

    if (FAILED(hr = SHCreateStreamOnFile(filename.c_str(), STGM_READ, &pStream)))
    {
        return bRet;
    }
    if (!GetDataContainer())
    {
        if (FAILED(hr = CreateXmlReader(__uuidof(IXmlReader), (void**)&pReader, nullptr)))
        {
            return bRet;
        }
        if (FAILED(hr = pReader->SetInput(pStream)))
        {
            return bRet;
        }
        bool inKey = false;
        wstring csKeyFoundStr;
        while (!pReader->IsEOF())
        {
            pReader->Read(&nodeType);
            switch (nodeType)
            {
            case XmlNodeType_Element:
                if (S_OK == pReader->GetLocalName(&pwszName, nullptr))
                {
                    if (true == isNodeInKeys(pwszName))
                    {
                        inKey = true;
                        csKeyFoundStr = pwszName;
                    }
                }
                break;
            case XmlNodeType_CDATA:
            case XmlNodeType_Text:
            {
                if (true == inKey)
                {
                    if (S_OK == pReader->GetValue(&pwszValue, nullptr))
                    {
                        GetDataContainer()->setkeyValue(csKeyFoundStr, pwszValue);
                        inKey = false;
                        bRet = true;
                    }
                }
            }
            break;
            default:
                break;
            }
        }
    }
    return bRet;
}
Beispiel #13
0
//
// Parse the XML data returned from Flickr, if error happens, return the error message.
//
std::wstring FlickrUploader::GetXmlElementValueByName(const std::wstring& xmlContent, const std::wstring& elementName, bool* errorFound)
{
    *errorFound = false;
    HGLOBAL memory;
    // Allocate a global memory for the xml content
    memory = ::GlobalAlloc(GMEM_MOVEABLE, xmlContent.length() * sizeof(wchar_t));
    void* data = ::GlobalLock(memory);
    // Fill memory
    ::memcpy(data, xmlContent.c_str(), xmlContent.length() * sizeof(wchar_t));
    ::GlobalUnlock(memory);

    // Create stream based on the allocated memory
    ComPtr<IStream> stream;
    HRESULT hr = ::CreateStreamOnHGlobal(memory, FALSE, &stream);

    // Create Xml Reader Input based on the stream
    ComPtr<IXmlReaderInput> readerInput;
    if (SUCCEEDED(hr))
    {
        hr = CreateXmlReaderInputWithEncodingCodePage(stream, 0, CP_WINNEUTRAL, false, 0, &readerInput);
    }
    // Create Xml Reader
    ComPtr<IXmlReader> reader;
    if (SUCCEEDED(hr))
    {
        hr = CreateXmlReader(IID_IXmlReader, reinterpret_cast<void**>(&reader), 0);
    }
    if (SUCCEEDED(hr))
    {
        hr = reader->SetInput(readerInput);
    }
    std::wstring resultString;
    if (SUCCEEDED(hr))
    {
        XmlNodeType nodeType;
        // Parse xml file
        bool found = false;
        while (S_OK == (hr = reader->Read(&nodeType)) && !found) 
        {
            switch (nodeType)
            {
            case XmlNodeType_Element:
                {
                    const wchar_t* name;
                    if (FAILED(hr = reader->GetQualifiedName(&name, nullptr)))
                    {
                        *errorFound = true;
                        resultString = L"Parsing content from Flickr failed unexpectedly.";
                        break;
                    }

                    if (wcscmp(name, elementName.c_str()) == 0)
                    {
                        // Read next node
                        reader->Read(&nodeType);
                        unsigned int len = 0;
                        const wchar_t* element = nullptr;
                        if (SUCCEEDED(reader->GetValue(&element, &len)))
                        {
                            // Find the value
                            resultString = element;
                            found = true;
                        }
                    }
                    else if (wcscmp(name, L"err") == 0) // We got an error code
                    {
                        *errorFound = true;
                    }
                    break;
                }
            case XmlNodeType_Attribute:
                {
                    if (*errorFound)
                    {
                        const wchar_t* name;
                        if (FAILED(hr = reader->GetQualifiedName(&name, nullptr)))
                        {
                            *errorFound = true;
                            resultString = L"Parsing content from Flickr failed unexpectedly.";
                            break;
                        }

                        if (wcscmp(name, L"msg") == 0)
                        {
                            unsigned int len = 0;
                            const wchar_t* element = nullptr;
                            if (SUCCEEDED(reader->GetValue(&element, &len)))
                            {
                                // Get the error message
                                resultString = element;
                                found = true;
                            }
                        }
                    }
                    break;
                }
            }
        }
    }
    return resultString;
}
int _tmain(int argc, WCHAR* argv[])
{
    HRESULT hr;
    CComPtr<IStream> pFileStream;
    CComPtr<IXmlReader> pReader;
    XmlNodeType nodeType;
    const WCHAR* pwszPrefix;
    const WCHAR* pwszLocalName;
    const WCHAR* pwszValue;
    UINT cwchPrefix;

    if (argc != 2)
    {
        wprintf(L"Usage: XmlLiteReader.exe name-of-input-file\n");
        return 0;
    }

    //Open read-only input stream
    if (FAILED(hr = SHCreateStreamOnFile(argv[1], STGM_READ, &pFileStream)))
    {
        wprintf(L"Error creating file reader, error is %08.8lx", hr);
        return -1;
    }

    if (FAILED(hr = CreateXmlReader(__uuidof(IXmlReader), (void**) &pReader, NULL)))
    {
        wprintf(L"Error creating xml reader, error is %08.8lx", hr);
        return -1;
    }

    if (FAILED(hr = pReader->SetProperty(XmlReaderProperty_DtdProcessing, DtdProcessing_Prohibit)))
    {
        wprintf(L"Error setting XmlReaderProperty_DtdProcessing, error is %08.8lx", hr);
        return -1;
    }

    if (FAILED(hr = pReader->SetInput(pFileStream)))
    {
        wprintf(L"Error setting input for reader, error is %08.8lx", hr);
        return -1;
    }

    //read until there are no more nodes
    while (S_OK == (hr = pReader->Read(&nodeType)))
    {
        switch (nodeType)
        {
        case XmlNodeType_XmlDeclaration:
            wprintf(L"XmlDeclaration\n");
            if (FAILED(hr = WriteAttributes(pReader)))
            {
                wprintf(L"Error writing attributes, error is %08.8lx", hr);
                return -1;
            }
            break;
        case XmlNodeType_Element:
            if (FAILED(hr = pReader->GetPrefix(&pwszPrefix, &cwchPrefix)))
            {
                wprintf(L"Error getting prefix, error is %08.8lx", hr);
                return -1;
            }
            if (FAILED(hr = pReader->GetLocalName(&pwszLocalName, NULL)))
            {
                wprintf(L"Error getting local name, error is %08.8lx", hr);
                return -1;
            }
            if (cwchPrefix > 0)
                wprintf(L"Element: %s:%s\n", pwszPrefix, pwszLocalName);
            else
                wprintf(L"Element: %s\n", pwszLocalName);

            if (FAILED(hr = WriteAttributes(pReader)))
            {
                wprintf(L"Error writing attributes, error is %08.8lx", hr);
                return -1;
            }

            if (pReader->IsEmptyElement() )
                wprintf(L" (empty)");
            break;
        case XmlNodeType_EndElement:
            if (FAILED(hr = pReader->GetPrefix(&pwszPrefix, &cwchPrefix)))
            {
                wprintf(L"Error getting prefix, error is %08.8lx", hr);
                return -1;
            }
            if (FAILED(hr = pReader->GetLocalName(&pwszLocalName, NULL)))
            {
                wprintf(L"Error getting local name, error is %08.8lx", hr);
                return -1;
            }
            if (cwchPrefix > 0)
                wprintf(L"End Element: %s:%s\n", pwszPrefix, pwszLocalName);
            else
                wprintf(L"End Element: %s\n", pwszLocalName);
            break;
        case XmlNodeType_Text:
        case XmlNodeType_Whitespace:
            if (FAILED(hr = pReader->GetValue(&pwszValue, NULL)))
            {
                wprintf(L"Error getting value, error is %08.8lx", hr);
                return -1;
            }
            wprintf(L"Text: >%s<\n", pwszValue);
            break;
        case XmlNodeType_CDATA:
            if (FAILED(hr = pReader->GetValue(&pwszValue, NULL)))
            {
                wprintf(L"Error getting value, error is %08.8lx", hr);
                return -1;
            }
            wprintf(L"CDATA: %s\n", pwszValue);
            break;
        case XmlNodeType_ProcessingInstruction:
            if (FAILED(hr = pReader->GetLocalName(&pwszLocalName, NULL)))
            {
                wprintf(L"Error getting name, error is %08.8lx", hr);
                return -1;
            }
            if (FAILED(hr = pReader->GetValue(&pwszValue, NULL)))
            {
                wprintf(L"Error getting value, error is %08.8lx", hr);
                return -1;
            }
            wprintf(L"Processing Instruction name:%S value:%S\n", pwszLocalName, pwszValue);
            break;
        case XmlNodeType_Comment:
            if (FAILED(hr = pReader->GetValue(&pwszValue, NULL)))
            {
                wprintf(L"Error getting value, error is %08.8lx", hr);
                return -1;
            }
            wprintf(L"Comment: %s\n", pwszValue);
            break;
        case XmlNodeType_DocumentType:
            wprintf(L"DOCTYPE is not printed\n");
            break;
        }
    }

    return 0;
}