I have this XML file below:
<catalog>
<book id="bk101">
<author> Gambardella, Matthew </author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications with XML.</description>
</book>
</catalog>
I would like to print the attribute inside the book node (that being the value of id, which is bk101), however I'm having trouble using the MSXML6 library to do so, and I would like to stick with it instead of changing to Rapid, etc.
Below is my code so far:
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#import <msxml6.dll> rename_namespace(_T("MSXML"))
#include<iostream>
#include<string>
int main(int argc, char* argv[]) {
HRESULT hr = CoInitialize(NULL);
if (SUCCEEDED(hr)) {
try {
MSXML::IXMLDOMDocument2Ptr xmlDoc;
MSXML::IXMLDOMNodePtr bookholder;
MSXML::IXMLDOMNodePtr author;
MSXML::IXMLDOMNodePtr title;
hr = xmlDoc.CreateInstance(__uuidof(MSXML::DOMDocument60),
NULL, CLSCTX_INPROC_SERVER);
// TODO: if (FAILED(hr))...
if (xmlDoc->load(_T("books.xml")) != VARIANT_TRUE) {
printf("Unable to load input.xml\n");
}
else {
printf("XML was successfully loaded\n");
xmlDoc->setProperty("SelectionLanguage", "XPath");
MSXML::IXMLDOMNodeListPtr booklist = xmlDoc->selectNodes("/catalog/*");
bookholder = booklist->Getitem(0);
//printf(bookholder->Getxml()+"\n"); //works till here
//printf(bookholder->; //what to do here to print attribute?
}
}
catch (_com_error& e) {
printf("ERROR: %ws\n", e.ErrorMessage());
}
CoUninitialize();
}
return 0;
}
Related
I want to change the title bar of calc.exe. I read that it's done via SetWindowTextA() but when I used this it only change the title of the preview (1) and I want to change title at (2) as well.
Can anyone explain for me why it change the title at (1) not (2) and how can I change the title at (2)
The Calculator title is Text Control Type retrieved using UI Automation. However according to Text Control Type, the IValueProvider is never supported by text controls. So you can’t.
Edit:
#include <Windows.h>
#include <UIAutomation.h>
#include <wchar.h>
int Element(IUIAutomation* automation)
{
// Get the element under the cursor
// Use GetPhysicalCursorPos to interact properly with
// High DPI
POINT pt;
GetPhysicalCursorPos(&pt);
IUIAutomationElement* pAtMouse;
HRESULT hr = automation->ElementFromPoint(pt, &pAtMouse);
if (FAILED(hr))
return hr;
// Get the element's name and print it
BSTR name;
hr = pAtMouse->get_CurrentName(&name);
if (SUCCEEDED(hr))
{
IUIAutomationTextPattern* pattern;
pAtMouse->GetCurrentPatternAs(UIA_TextPatternId, IID_IUIAutomationTextPattern,(void**)&pattern);
//TODO
wprintf(L"Element's Name: %s \n", name);
SysFreeString(name);
}
// Get the element's Control Type (in the current languange)
// and print it
BSTR controlType;
hr = pAtMouse->get_CurrentLocalizedControlType(&controlType);
if (SUCCEEDED(hr))
{
wprintf(L"Element's Control Type: %s \n", controlType);
SysFreeString(controlType);
}
// Clean up our COM pointers
pAtMouse->Release();
return hr;
}
int main(int argc, TCHAR* argv[])
{
// Initialize COM and create the main Automation object
IUIAutomation* g_pAutomation;
CoInitialize(NULL);
HRESULT hr = CoCreateInstance(__uuidof(CUIAutomation), NULL,
CLSCTX_INPROC_SERVER, __uuidof(IUIAutomation),
(void**)&g_pAutomation);
if (FAILED(hr))
return (hr);
bool quit = false;
while (!quit)
{
SHORT leftControlMod = GetAsyncKeyState(VK_LCONTROL);
if (leftControlMod != 0)
{
Element(g_pAutomation);
}
quit = GetAsyncKeyState(VK_ESCAPE);
}
g_pAutomation->Release();
CoUninitialize();
return 0;
}
I have been trying lately to get a grasp on the Windows Property System. I implemented a custom file type(Property Handler, Thumbnail Handler, Preview Handler) and I want to hide System.Size property for my file type on Windows Explorer(Details Tab on Properties dialogbox and Size Column on Details View Mode).I used the following code but no result. Is it possible to hide size property? Maybe I should write Shell Folder extension.
#include <shobjidl.h>
#include <propsys.h>
#include <propvarutil.h>
#include <propkey.h>
#include <strsafe.h>
#pragma comment(lib,"propsys.lib")
HRESULT SetPropertyValue(PCWSTR pszFilename, PCWSTR pszCanonicalName, PCWSTR pszValue)
{
// Convert the Canonical name of the property to PROPERTYKEY
PROPERTYKEY key;
HRESULT hr = PSGetPropertyKeyFromName(pszCanonicalName, &key);
if (SUCCEEDED(hr))
{
IPropertyStore* pps = NULL;
hr = SHGetPropertyStoreFromParsingName(pszFilename, NULL, gpsFlags, IID_PPV_ARGS(ppps));
if (SUCCEEDED(hr))
{
PROPVARIANT propvarValue = { 0 };
hr = InitPropVariantFromString(pszValue, &propvarValue);
if (SUCCEEDED(hr))
{
hr = PSCoerceToCanonicalValue(key, &propvarValue);
if (SUCCEEDED(hr))
{
// Set the value to the property store of the item.
hr = pps->SetValue(key, propvarValue);
if (SUCCEEDED(hr))
{
// Commit does the actual writing back to the file stream.
hr = pps->Commit();
if (SUCCEEDED(hr))
{
wprintf(L"Property %s value %s written successfully \n", pszCanonicalName, pszValue);
}
else
{
wprintf(L"Error %x: Commit to the propertystore failed.\n", hr);
}
}
else
{
wprintf(L"Error %x: Set value to the propertystore failed.\n", hr);
}
}
PropVariantClear(&propvarValue);
}
pps->Release();
}
else
{
wprintf(L"Error %x: getting the propertystore for the item.\n", hr);
}
}
else
{
wprintf(L"Invalid property specified: %s\n", pszCanonicalName);
}
return hr;
}
int wmain(int argc, wchar_t* argv[])
{
if (SUCCEEDED(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE)))
{
SetPropertyValue(L"FullFilePath",L"System.Size", L"0");
CoUninitialize();
}
return 0;
}
I'm developing a sample code to get information about the Windows Updates Monitoring.
I bumped into Windows Update Agent APIs. link: http://msdn.microsoft.com/en-us/library/windows/desktop/aa387099(v=vs.85).aspx
But I'm not able to find any APIs for win32. I find only C#/.NET Interfaces.
Are there any corresponding win32 APIs?
Specifically I want to find out the "release date" of a windows update/patch.
Look forward to any suggestions and guidance.
Srivathsa
The WUA API includes a set of COM interfaces which can be used from C++ Apps, so try these IUpdateSearcher, IUpdateSession and IUpdate.
Check this sample c++ application which retrieve the updates and the date of release.
#include "stdafx.h"
#include <wuapi.h>
#include <iostream>
#include <ATLComTime.h>
#include <wuerror.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
HRESULT hr;
hr = CoInitialize(NULL);
IUpdateSession* iUpdate;
IUpdateSearcher* searcher;
ISearchResult* results;
BSTR criteria = SysAllocString(L"IsInstalled=1 or IsHidden=1 or IsPresent=1");
hr = CoCreateInstance(CLSID_UpdateSession, NULL, CLSCTX_INPROC_SERVER, IID_IUpdateSession, (LPVOID*)&iUpdate);
hr = iUpdate->CreateUpdateSearcher(&searcher);
wcout << L"Searching for updates ..."<<endl;
hr = searcher->Search(criteria, &results);
SysFreeString(criteria);
switch(hr)
{
case S_OK:
wcout<<L"List of applicable items on the machine:"<<endl;
break;
case WU_E_LEGACYSERVER:
wcout<<L"No server selection enabled"<<endl;
return 0;
case WU_E_INVALID_CRITERIA:
wcout<<L"Invalid search criteria"<<endl;
return 0;
}
IUpdateCollection *updateList;
IUpdate *updateItem;
LONG updateSize;
BSTR updateName;
DATE retdate;
results->get_Updates(&updateList);
updateList->get_Count(&updateSize);
if (updateSize == 0)
{
wcout << L"No updates found"<<endl;
}
for (LONG i = 0; i < updateSize; i++)
{
updateList->get_Item(i,&updateItem);
updateItem->get_Title(&updateName);
updateItem->get_LastDeploymentChangeTime(&retdate);
COleDateTime odt;
odt.m_dt=retdate;
wcout<<i+1<<" - "<<updateName<<" Release Date "<< (LPCTSTR)odt.Format(_T("%A, %B %d, %Y"))<<endl;
}
::CoUninitialize();
wcin.get();
return 0;
}
I would like to set the Default Search Engine Provider of IE with IOpenServiceManager::InstallService:
Belong to the link http://www.opensearch.org/Specifications/OpenSearch/1.1#OpenSearch_description_elements. I created the SearchProviderInfo.xml like this:
<?xml version="1.0" encoding="UTF-8"?> <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"> <ShortName>Web Search</ShortName> <Description>Use Example.com to search the Web.</Description> <Tags>example web</Tags> <Contact>admin#example.com</Contact> <Url type="application/atom+xml" template="http://example.com/?q={searchTerms}&pw={startPage?}&format=atom"/> <Url type="application/rss+xml" template="http://example.com/?q={searchTerms}&pw={startPage?}&format=rss"/> <Url type="text/html" template="http://example.com/?q={searchTerms}&pw={startPage?}"/> <LongName>Example.com Web Search</LongName> <Image height="64" width="64" type="image/png">http://example.com/websearch.png</Image> <Image height="16" width="16" type="image/vnd.microsoft.icon">http://example.com/websearch.ico</Image> <Query role="example" searchTerms="cat" /> <Developer>Example.com Development Team</Developer> <Attribution> Search data Copyright 2005, Example.com, Inc., All Rights Reserved </Attribution> <SyndicationRight>open</SyndicationRight> <AdultContent>false</AdultContent> <Language>en-us</Language> <OutputEncoding>UTF-8</OutputEncoding> <InputEncoding>UTF-8</InputEncoding> </OpenSearchDescription>
Belong to the link http://msdn.microsoft.com/en-us/library/cc849088%28v=vs.85%29.aspx. I create the project "SetDefaultHelper" like this:
#include <windows.h>
#include <atlbase.h>
#include <wininet.h>
#include <urlmon.h>
#include <string>
#include "openservice.h"
#pragma comment(lib, "urlmon.lib")
void DisplayUsage()
{
wprintf(L"\r\nSetDefaultHelper.exe -- Call SetDefault API on a search provider");
wprintf(L"\r\n");
wprintf(L"\r\nUSAGE: SetDefaultHelper.exe <option>");
wprintf(L"\r\n");
wprintf(L"\r\nOptions (these are mutually exclusive!):");
wprintf(L"\r\n");
wprintf(L"\r\n /guid <guid> GUID of an installed search provider");
wprintf(L"\r\n /url <url> URL of an OpenSearch Description file");
wprintf(L"\r\n");
}
int __cdecl wmain(__in int argc, __in_ecount(argc) WCHAR* argv[])
{
HRESULT hr = E_FAIL;
BOOL fComInitialized = FALSE;
if (3 != argc)
{
DisplayUsage();
}
else if (SUCCEEDED(CoInitialize(NULL)))
{
fComInitialized = TRUE;
CComPtr<IOpenServiceManager> spManager;
hr = spManager.CoCreateInstance(CLSID_OpenServiceManager);
if (SUCCEEDED(hr))
{
CComPtr<IOpenService> spService;
if (0 == _wcsicmp(argv[1], L"/guid"))
{
// Get an IOpenService pointer from the GUID.
WCHAR szEscaped[INTERNET_MAX_URL_LENGTH] = L"";
DWORD cchEscaped = ARRAYSIZE(szEscaped);
hr = UrlEscape(argv[2], szEscaped, &cchEscaped, URL_ESCAPE_SEGMENT_ONLY);
if (SUCCEEDED(hr))
{
std::wstring wsOsid(L"x-osid:1:search:");
wsOsid += szEscaped;
hr = spManager->GetServiceByID(wsOsid.c_str(), &spService);
}
}
else if (0 == _wcsicmp(argv[1], L"/url"))
{
// Install the provider to get an IOpenService pointer.
//CComPtr<IUri> spUri;
//hr = CreateUri(argv[2], 0, 0, &spUri);
//if (SUCCEEDED(hr))
//{
hr = spManager->InstallService(argv[2], &spService);
//}
}
else
{
DisplayUsage();
hr = E_FAIL;
}
if (SUCCEEDED(hr))
{
hr = spService->SetDefault(TRUE, NULL);
}
}
}
if (fComInitialized)
{
CoUninitialize();
}
return hr;
}
I build the project ok. Both file SetDefaultHelper.exe and SearchProviderInfo.xml are same folder. In the project setting, set Configuration Properties > Debugging > Commands Arguments = /url absolutePaht/searchProvider.xml. Then run debug (F10), at line "hr = CreateUri(argv[2], 0, 0, &spUri);", the rusult hr is so stranger. I don't know why. Can you help me?
Thank you very much.
[Resolved]:
1. Don't need CreateUri //commented
2. Use a absolutely path.
Use absolute path and UrlCreateFromPath to create a file:/// like URL, pass that URL to InstallService.
Between, it seems that your XML has error.
WCHAR szURL[MAX_PATH] = L"";
DWORD cchURL = ARRAYSIZE(szURL);
hr = ::UrlCreateFromPath(argv[2], szURL, &cchURL, 0);
if (SUCCEEDED(hr))
{
hr = spManager->InstallService(argv[2], &spService);
// Now we can set it as the default.
if (SUCCEEDED(hr))
{
hr = spService->SetDefault(TRUE, NULL);
if (hr == OS_E_CANCELLED)
{
hr = E_ACCESSDENIED; // by the user!
}
}
}
I'm using C++ with MSXML and want to get data from XML file as Base64. I'm using this code:
hr = nodeList->get_item((long)i, (IXMLDOMNode **)&vXMLNode);
if ( FAILED(hr) )
throw "Unable to retrieve child node";
vXMLNode->put_dataType(_bstr_t("bin.base64"));
hr = vXMLNode->get_nodeTypedValue(&varValue);
if ( FAILED(hr) )
throw "Unable to retrieve 'xmltext' text";
So vXMLNode is a child node with data. Node type of vXMLNode is NODE_ELEMENT. If I check data type for this node, I get VT_NULL. Therefore I get my data as a string.
What is wrong in my code?
I believe the problem lies outside of your supplied sample code. Here's a working console program that uses nodeTypedValue. I hope this helps.
// Base64CPP.cpp : Defines the entry point for the console application.
// NOTE:
// This code is provided as is in the form of a sample with no warranties of any kind,
// either expressed or implied for any purpose. Use at your own risk.
#include "stdafx.h"
#include <TCHAR.H>
#include <stdio.h>
#include <sys/stat.h>
#include <fstream>
#include <string.h>
#include <atlbase.h>
#import <msxml4.dll> named_guids
using namespace MSXML2;
inline void EVAL_HR( HRESULT _hr )
{ if FAILED(_hr) throw(_hr); }
// Binary to Base64 Encoding
bool DoEncoding(LPCTSTR lpszXMLFile, LPCTSTR lpszBinFile)
{
bool bRetVal = false;
try
{
long lFileSize;
struct stat fileSizeVal;
// Get the file size
if (stat(lpszBinFile, &fileSizeVal) == 0)
{
lFileSize = fileSizeVal.st_size;
if(lFileSize <= 0)
return false;
}
else
return false;
// Instantiate XML DOMDocument
CComPtr<IXMLDOMDocument2> spXMLDoc;
CComPtr<MSXML2::IXMLDOMElement> spDataElement;
HRESULT hr = spXMLDoc.CoCreateInstance(CLSID_DOMDocument40);
EVAL_HR(hr);
spXMLDoc->loadXML(_T("<?xml version='1.0' encoding='UTF-8'?> <Data/>"));
// Prepare the top node to store binary data as base64
spDataElement = spXMLDoc->documentElement;
ATLASSERT(spDataElement != NULL && _T("Failed to get document element."));
hr = spDataElement->put_dataType(CComBSTR(_T("bin.base64")));
EVAL_HR(hr);
// Read the file into memory
std::ifstream binDataFile;
binDataFile.open(lpszBinFile, std::ios::binary);
binDataFile.seekg(std::ios::beg);
SAFEARRAY* psa = SafeArrayCreateVector( VT_UI1, 0L, lFileSize);
binDataFile.read((char*)psa->pvData, lFileSize);
binDataFile.close();
// Save the binary data into Data node
VARIANT var;
VariantInit(&var);
var.parray = psa;
var.vt = (VT_ARRAY | VT_UI1 );
spDataElement->nodeTypedValue = var;
// Save the XML Document
spXMLDoc->save(lpszXMLFile);
bRetVal = true;
}
catch(int)
{
//TODO: Error handling
printf(_T("Exception raised!"));
}
return bRetVal;
}
// Base64 to binary decoding
bool DoDecoding(LPCTSTR lpszXMLFile, LPCTSTR lpszBinFile)
{
bool bRetVal = false;
try
{
// Instantiate DOMDocument and load XML file
CComPtr<IXMLDOMDocument2> spXMLDoc;
CComPtr<MSXML2::IXMLDOMElement> spDataElement;
HRESULT hr = spXMLDoc.CoCreateInstance(CLSID_DOMDocument40);
EVAL_HR(hr);
CComVariant vtFileName = CComBSTR(lpszXMLFile);
spXMLDoc->load(vtFileName);
// ASSUMPTION: documentElement (top element) contains base64 data
spDataElement = spXMLDoc->documentElement;
ATLASSERT(spDataElement != NULL && _T("Failed to get document element."));
// Prepare the file for writing
std::ofstream binDataFile (lpszBinFile, std::ios::out | std::ios::binary);
// Save the binary data into data file
long lDataLength=0;
hr = SafeArrayGetUBound(spDataElement->nodeTypedValue.parray, 1, &lDataLength);
EVAL_HR(hr);
lDataLength++;
binDataFile.write((char*)(spDataElement->nodeTypedValue.parray->pvData), lDataLength);
binDataFile.close();
bRetVal = true;
}
catch(int)
{
//TODO: Error handling
printf(_T("Exception raised!"));
}
return bRetVal;
}
int main(int argc, char* argv[])
{
if(argc < 4)
{//insufficient parameters
printf(_T("\nSample app to encode/decode binary data as base64 XML using MSXML.\n"));
printf(_T("\nUsage:\tBase64CPP.exe <e>|<d> <XMLFileName> <BinaryDataFile>"));
printf(_T("\n\nExamples:"));
printf(_T("\n\tEncode binary data in 1.jpg and save as Base64 into 1.xml:"));
printf(_T("\n\t\tBase64CPP.exe e c:\\1.xml c:\\1.jpg\n"));
printf(_T("\n\tDecode base64 data in 1.xml and save as binary into 2.jpg:"));
printf(_T("\n\t\tBase64CPP.exe d c:\\1.xml c:\\2.jpg\n\n"));
return -1;
}
try
{
HRESULT hr = CoInitialize(NULL);
EVAL_HR(hr);
if(_tcsicmp(argv[1], _T("e")) == 0)
{
if(DoEncoding(argv[2], argv[3]))
printf(_T("Success. See %s for results."), argv[2]);
else
printf(_T("Failed."));
}
else
{
if(DoDecoding(argv[2], argv[3]))
printf(_T("Success. See %s for results."), argv[3]);
else
printf(_T("Failed."));
}
}
catch(int)
{
//TODO: Error handling
printf(_T("Exception raised!"));
}
CoUninitialize();
getchar();
return 0;
}