|
// RootElement.cpp
//
// written by: PJ Arends
// License Ms-PL
#include "stdafx.h"
#include "RootElement.h"
using namespace Elmax;
#include <boost/Filesystem.hpp>
using namespace boost::filesystem;
bool RootElement::LoadFile(const std::wstring &FilePath)
{
bool retval = false;
UnloadFile();
HRESULT hr = m_ptrDoc.CreateInstance(__uuidof(MSXML2::DOMDocument30));
#ifdef _DEBUG
if (hr == CO_E_NOTINITIALIZED)
{
throw std::exception("CoInitialize has not been called for this thread");
}
#endif
if (SUCCEEDED(hr))
{
path Path(FilePath);
if (exists(Path) && is_regular_file(Path))
{ // Open existing file
variant_t varFile(FilePath.c_str());
// load will fail if the file has malformed xml
if (m_ptrDoc->load(varFile) == VARIANT_TRUE)
{
SetConverter(REGEX_CONV);
SetDomDoc(m_ptrDoc);
m_FilePath = FilePath;
retval = true;
}
}
else
{
// create an empty document
// these methods should not fail so don't inspect result
m_ptrDoc->async = VARIANT_FALSE;
m_ptrDoc->validateOnParse = VARIANT_FALSE;
m_ptrDoc->resolveExternals = VARIANT_FALSE;
//MSXML2::IXMLDOMProcessingInstructionPtr pi = m_pDoc->createProcessingInstruction(L"xml", L" version='1.0' encoding='UTF-8'");
//m_pDoc->appendChild(pi);
m_FilePath = FilePath;
retval = true;
}
}
return retval;
}
bool RootElement::CanWriteFile(const std::wstring& FilePath, bool OverWrite, bool CreateFolder)
{
path Path(FilePath);
if (exists(Path))
{
if (is_regular_file(Path))
{
return OverWrite;
}
return false;
}
path Folder = Path.parent_path();
if (exists(Folder))
{
return true;
}
if (CreateFolder)
{
return create_directories(Folder);
}
return false;
}
bool RootElement::SaveFile(const std::wstring& FilePath, bool OverWrite, bool CreateFolder)
{
if (NULL == m_ptrDoc)
{
return false;
}
if (!FilePath.empty())
{
m_FilePath = FilePath;
}
if (CanWriteFile(m_FilePath, OverWrite, CreateFolder))
{
variant_t varFile(m_FilePath.c_str());
Elmax::Document doc(m_ptrDoc);
return doc.PrettySave(m_FilePath, L"1.0", true);
}
return false;
}
bool RootElement::UnloadFile()
{
m_ptrDoc = NULL; // calls Release() for us
m_FilePath.clear();
return true;
}
RootElement::~RootElement()
{
UnloadFile();
}
RootElement& RootElement::operator = (const RootElement &other)
{
UnloadFile();
m_ptrDoc = other.m_ptrDoc;
m_FilePath = other.m_FilePath;
return *this;
}
bool RootElement::SetFilePath(std::wstring FilePath)
{
if (NULL == m_ptrDoc)
{
return false;
}
m_FilePath = FilePath;
return true;
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Shao Voon is from Singapore. His interest lies primarily in computer graphics, software optimization, concurrency, security, and Agile methodologies.
In recent years, he shifted focus to software safety research. His hobby is writing a free C++ DirectX photo slideshow application which can be viewed
here.