I need to write code that identifies a XML node "type". I have no prior knowledge of the XML structure. I need to identify if a node is an "attribute node" if a node is a "value" node or a "children" node.
For Example:
<A>
<B>ValB</B>
<C>
<D>ValC</D>
</C>
<E atrD1="attrD1Val" arreD2="arrD2Val">
<F>ValF</F>
</E>
</A>
In the above example <B>
is a "value" node, <C>
is a "Children" node, and <E>
is an "attribute" node.
Note that <E>
should not be designated as "children" node although technically it is. This means that node types are mutual exclusive (must be only one of the three type).
Assuming the following code:
int main() {
CoInitialize(NULL);
IXMLDOMDocument* pXMLDoc = nullptr;
IXMLDOMNode* pNode = nullptr;
HRESULT hr = CoCreateInstance(CLSID_DOMDocument60, NULL, CLSCTX_INPROC_SERVER, IID_IXMLDOMDocument, (void**)&pXMLDoc);
if (SUCCEEDED(hr)) {
VARIANT_BOOL vbSuccess;
hr = pXMLDoc->loadXML(_bstr_t(
L"<A>"
L" <B>ValB</B>"
L" <C>"
L" <D>ValC</D>"
L" </C>"
L" <E atrD1=\"attrD1Val\" arreD2=\"arrD2Val\">"
L" <F>ValF</F>"
L" </E>"
L"</A>"), &vbSuccess); // Load XML from string
if (SUCCEEDED(hr) && vbSuccess == VARIANT_TRUE) {
// Check node B
hr = pXMLDoc->selectSingleNode(_bstr_t(L"/A/B"), &pNode);
if (SUCCEEDED(hr) && pNode != nullptr) {
CheckNodeType(pNode);
pNode->Release();
}
// Check node C
hr = pXMLDoc->selectSingleNode(_bstr_t(L"/A/C"), &pNode);
if (SUCCEEDED(hr) && pNode != nullptr) {
CheckNodeType(pNode);
pNode->Release();
}
// Check node E
hr = pXMLDoc->selectSingleNode(_bstr_t(L"/A/E"), &pNode);
if (SUCCEEDED(hr) && pNode != nullptr) {
CheckNodeType(pNode);
pNode->Release();
}
}
pXMLDoc->Release();
}
CoUninitialize();
return 0;
}
Now, how do I go about writing CheckNodeType(IXMLDOMNode* pNode)
.
The main issue is distinguishing between "Children" and "Value" node types, as attributes is a trivial check:
I tried:
BSTR bstrText;
hr = pNode->get_text(&bstrText);
This returns the entire sub XML
I tried:
IXMLDOMNode *txtNode;
if (SUCCEEDED(pNode->get_firstChild(&txtNode)) && (txtNode != nullptr))
{
DOMNodeType nodeType;
if (SUCCEEDED(txtNode->get_nodeType(&nodeType))
{
if (nodeType == NODE_TEXT)
{
// This is a "value" node.
}
else
{
// This is a "children" node.
}
}
}
For some reason this did not work.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744149024a4560560.html
评论列表(0条)