使用cpp更新和保存xml文档

时间:2018-08-07 10:37:57

标签: c++ xml

我是CPP编程的新手。在更新XML文件的属性之一后,谁能帮助我保存/更新XML文件? 我有一个现有的xml文件,用于cpp测试用例之一。每次我运行测试用例时,文件中的属性之一应被更新。 xml文件的内容如下:

<?xml version="1.0" encoding="utf-8"?>
<Abc id1="1" Version="1.0.0.0" id2="1">
   <d>abc<d/>
    <e>xyz<e/>
</Abc>

下面是我编写的在控制台应用程序中有效的方法。但是当我从测试用例中调用它时不起作用。

void UpdateXml(std::string FileName,std::string attrVal){
IXMLDOMNodeList * nodeList;
IXMLDOMNodeList *childList;
IXMLDOMNode * node;

CComPtr<IXMLDOMDocument> iXMLDoc;
CoInitialize(nullptr);
HRESULT hr = iXMLDoc.CoCreateInstance(__uuidof(DOMDocument));
if (FAILED(hr))
{
    std::wcout<<L"Could not create instance of DOMDocument" << std::endl;
}
//#ifdef UNDER_CE (not commented in original code)
iXMLDoc->put_async(VARIANT_FALSE);
CComQIPtr<IObjectSafety, &IID_IObjectSafety> isafe(iXMLDoc);
if (iSafety)
{
    DWORD dwSupported, dwEnabled;
    isafe->GetInterfaceSafetyOptions(IID_IXMLDOMDocument,
        &dwSupported, &dwEnabled);
    isafe->SetInterfaceSafetyOptions(IID_IXMLDOMDocument,
        dwSupported, 0);
}
//#endif (not commented in original code)

// Load the file. 
VARIANT_BOOL bSuccess = false;
// Can load it from a url/filename...

hr = iXMLDoc->load(CComVariant(FileName.c_str()), &bSuccess);
if (!SUCCEEDED(hr))
{
    std::wcout<<std::endl << L"Could not load XML" << std::endl;
}

// Get a pointer to the root
CComPtr<IXMLDOMElement> iRootElm;
hr = iXMLDoc->get_documentElement(&iRootElm);
if (!SUCCEEDED(hr))
{
    std::wcout<<std::endl << L"Could not get root document element" << 
 std::endl;
}
BSTR bstrVersion=L"Version";
VARIANT variantVal=CComVariant(attrVal.c_str());
hr=iRootElm->setAttribute(bstrVersion,variantVal);
if(!SUCCEEDED(hr))
{
    cout<<"\n**********Could not set the attribute****************\n";
}
else
{
    cout<<"\n**********setting attribute successful****************\n";
}

hr=iXMLDoc->save(CComVariant(FileName.c_str()));
if(!SUCCEEDED(hr))
{
    cout<<"\nCould not save the xml Doc\n";
}
else
{
    cout<<"\n Successfully saved the xml doc";
}

nodeList = nullptr;
childList = nullptr;
node = nullptr;
iRootElm = nullptr;
iXMLDoc = nullptr;
}

在控制台应用程序中:从主方法中,我这样调用它:UpdateXml("Folder\\abc.xml","435435"); 当我在另一个项目中实现并从测试用例中调用它时,save方法会成功,但方法相同,但输出始终是“无法保存Xml Doc”(如打印所示)。

有人可以在这方面帮助我吗?

0 个答案:

没有答案