令人惊讶的IXMLDOMDocument :: selectNodes并没有按预期工作。我知道这是因为xmlns =" http://stackoverflow.com/questions/ask"但我不知道如果xmlns存在,如何使其工作。
V_BSTR(&varParam) = SysAllocString(LR"iPhone5s(XPath)iPhone5s");
V_VT(&varParam) = VT_BSTR;
hr = ptrXMLDom->setProperty(L"SelectionLanguage", varParam);
ptrXMLDom->selectNodes(L"//bookstore", &ptrDomNodeList);
ptrDomNodeList->get_length(&len);//the value is always 0
备注:xml是只读的。不要告诉我修改原始XML。
Here is my code:
#include <msxml6.h>
#include <msxml2.h>//necessary in Visual Studio 2013
HRESULT hr = CoInitialize(NULL);
HRESULT hr = CoCreateInstance(__uuidof(DOMDocument60), NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(ppDoc));
if (SUCCEEDED(hr))
{
// these methods should not fail so don't inspect result
(*ppDoc)->put_async(VARIANT_FALSE);
(*ppDoc)->put_validateOnParse(VARIANT_FALSE);
(*ppDoc)->put_resolveExternals(VARIANT_FALSE);
(*ppDoc)->put_preserveWhiteSpace(VARIANT_TRUE);
}
HRESULT hr = S_OK;
IXMLDOMDocument2 *ptrXMLDom = NULL;
VARIANT_BOOL varBool = VARIANT_FALSE;
BSTR bstrXML = nullptr;
VARIANT varParam;
VariantInit(&varParam);
V_BSTR(&varParam) = SysAllocString(LR"iPhone5s(E:\Work\book.xml)iPhone5s");
V_VT(&varParam) = VT_BSTR;
hr = ptrXMLDom->load(varParam, &varBool);
V_BSTR(&varParam) = SysAllocString(LR"iPhone5s(XPath)iPhone5s");
V_VT(&varParam) = VT_BSTR;
hr = ptrXMLDom->setProperty(L"SelectionLanguage", varParam);
ptrXMLDom->selectNodes(L"//bookstore", &ptrDomNodeList);
ptrDomNodeList->get_length(&len);//the value is always 0
CoUninitialize();
这是xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Copyright w3school.com.cn -->
<!-- W3School.com.cn bookstore example -->
<bookstore xmlns="http://stackoverflow.com/questions/ask" version="1.0">
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
</bookstore>
答案 0 :(得分:1)
我自己找到了答案。
V_BSTR(&varParam) = SysAllocString(LR"iPhone5s(xmlns:pf='http://stackoverflow.com/questions/ask')iPhone5s");
V_VT(&varParam) = VT_BSTR;
hr = ptrXMLDom->setProperty(L"SelectionNamespaces", varParam);
ptrXMLDom->selectNodes(L"//pf:bookstore/pf:book", &ptrDomNodeList);
ptrDomNodeList->get_length(&len);//4