0
我知道使用JS的there is an example in stackoverflow,但我需要使用C++完成此操作,並且由於一個奇怪的原因,我無法使用put_nodeValue()將名稱空間添加到根元素,如果屬性名稱前綴爲「xmlns:」。使用C++在IXMLDOMDocument根元素中添加命名空間
所以,我需要這樣的:
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/">
<media:group />
<media:group />
</entry>
我用下面的代碼嘗試:
HRESULT hr = S_OK;
IXMLDOMDocument *doc;
IXMLDOMNode *entryElement;
IXMLDOMNode *groupElement;
IXMLDOMNode *groupElement2;
IXMLDOMNode *titleElement;
IXMLDOMNode *mediaAttribute;
// Initialize ...
hr = CoInitialize(NULL);
assert(hr == S_OK);
// Create (root) document
hr = CoCreateInstance(
CLSID_DOMDocument30,
NULL,
CLSCTX_INPROC_SERVER,
IID_IXMLDOMDocument,
(void**)&doc);
assert(hr == S_OK);
// Define namespaces
BSTR atomNamespace = L"http://www.w3.org/2005/Atom";
BSTR mediaNamespace = L"http://search.yahoo.com/mrss/";
// Define types
VARIANT elementType;
VariantInit(&elementType);
V_VT(&elementType) = VT_INT;
V_INT(&elementType) = NODE_ELEMENT;
VARIANT attributeType;
VariantInit(&attributeType);
V_VT(&attributeType) = VT_INT;
V_INT(&attributeType) = NODE_ATTRIBUTE;
// Add "entry" element
BSTR nodeName = L"entry";
hr = doc->createNode(elementType, nodeName, atomNamespace, &entryElement);
assert(hr == S_OK);
hr = doc->appendChild(entryElement, NULL);
assert(hr == S_OK);
// Add "media" namespace to "entry" element
nodeName = L"xmlns:media";
doc->createNode(attributeType, nodeName, atomNamespace, &mediaAttribute);
IXMLDOMNamedNodeMap *attributes;
entryElement->get_attributes(&attributes);
IXMLDOMNode *newAttribute;
hr = attributes->setNamedItem(mediaAttribute, &newAttribute);
assert(hr == S_OK);
VARIANT nodeValue;
VariantInit(&nodeValue);
V_VT(&nodeValue) = VT_BSTR;
V_BSTR(&nodeValue) = mediaNamespace;
hr = newAttribute->put_nodeValue(nodeValue);
assert(hr == S_OK);
// Add "group" element
nodeName = L"media:group";
hr = doc->createNode(elementType, nodeName, mediaNamespace, &groupElement);
assert(hr == S_OK);
hr = entryElement->appendChild(groupElement, NULL);
assert(hr == S_OK);
// Add second "group" element
nodeName = L"media:group";
hr = doc->createNode(elementType, nodeName, mediaNamespace, &groupElement2);
assert(hr == S_OK);
hr = entryElement->appendChild(groupElement2, NULL);
assert(hr == S_OK);
任何想法?我正在使用MSXML6。