2016-11-24 185 views
1

我使用Visual Studio C++與MSXML導入(#import「msxml6.dll」)來創建使用智能指針的xml文檔。MSXML C++聲明默認名稱空間

我使用setProperty()函數創建的命名空間,我再添加相應的屬性添加到文檔元素,但是當我試圖聲明默認名稱空間的所有文檔元素下面的元素都有xmlns=""加入到他們的屬性。

這裏是我的代碼:

// Macro to check HRESULT 
#define CheckHr(myHr) do{ hr = myHr; if(FAILED(hr)) throw _com_error(hr); }while(0) 

void makeMyXml() 
{ 
HRESULT hr{ S_OK }; 
MSXML2::IXMLDOMDocument3Ptr xDoc{ NULL }; 

try 
{ 
    // Create document 
    CheckHr(xDoc.CreateInstance(__uuidof(MSXML2::DOMDocument60))); 

    // Add namespaces 
    CheckHr(xDoc->setProperty(L"SelectionNamespaces", _T("xmlns=\"http://myDefaultNamespaceURL\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""))); 

    // Add document element 
    CheckHr(xDoc->appendChild(xDoc->createElement(_T("root")))); 

    // Add namespace attributes to root 
    CheckHr(xDoc->GetdocumentElement()->setAttribute(_T("xmlns"), _T("http://myDefaultNamespaceURL"))); 
    CheckHr(xDoc->GetdocumentElement()->setAttribute(_T("xmlns:xsi"), _T("http://www.w3.org/2001/XMLSchema-instance"))); 
    CheckHr(xDoc->GetdocumentElement()->setAttribute(_T("xsi:schemaLocation"), _T("http://schemaLocationValue"))); 

    CheckHr(xDoc->GetdocumentElement()->appendChild(xDoc->createElement(_T("exampleElement")))); 

    CheckHr(xDoc->save("test.xml")); 

} 
catch (_com_error &e) 
{ 
    // handle any thrown com errors here 
} 

return; 
} 

的XML這造成這樣的容貌:

<root xmlns="http://myDefaultNamespaceURL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schemaLocationValue"> 
    <exampleElement xmlns=""/> 
</root> 

我一直沒能找到一種方法,只是有<exampleElement/>代替<exampleElement xmlns=""/>

回答

1

使用MSXML,要在名稱空間中創建元素或屬性,需要使用createNode方法https://msdn.microsoft.com/en-us/library/ms757901(v=vs.85).aspx,其中使用e 。G。 xDoc->createNode(1, "root", "http://myDefaultNamespaceURL")在命名空間http://myDefaultNamespaceURL中創建一個元素。確保你使用相同的名字空間中的所有後代元素。您還可以使用createNode在名稱空間中創建屬性,例如createNode->(2, "xsi:schemaLocation", "http://www.w3.org/2001/XMLSchema-instance"),然後將其添加到元素的屬性。

的W3C DOM 2級和3具有感知名稱空間createElementNSsetAttributeNS在XML名稱空間,但不同於之前的水平了MSXML API日期的情況下使用,並沒有更新,符合W3C DOM,它唯一的命名空間感知方法是createNode。方法createElementsetAttribute基本上僅用於創建沒有名稱空間的XML。

另請參閱http://blogs.msmvps.com/martin-honnen/2009/04/14/creating-xml-with-namespaces-with-javascript-and-msxml/它使用JScript與MSXML,但顯然問題和解決方案與正確的API使用相同。

+0

這很好,但我該如何刪除它。基本上我有一個第三方應用程序崩潰時,有一個xmlns標籤,所以它需要被刪除。我如何阻止MSXML將其插入到每個標籤中。我絕對不想在那裏。有什麼辦法可以壓制它嗎? – Owl

+0

@Owl,考慮用必要的細節提出一個新問題。 –