1 #include "stdafx.h" 2 #include "SimpleXML.h" 3 4 CSimpleXML(const wstring & xml_path)5CSimpleXML::CSimpleXML(const wstring & xml_path) 6 { 7 ifstream file_stream{ xml_path }; 8 if (file_stream.fail()) 9 { 10 return; 11 } 12 //读取文件内容 13 string xml_str; 14 while (!file_stream.eof()) 15 { 16 xml_str.push_back(file_stream.get()); 17 } 18 xml_str.pop_back(); 19 if (!xml_str.empty() && xml_str.back() != L'\n') //确保文件末尾有回车符 20 xml_str.push_back(L'\n'); 21 //转换成Unicode 22 m_xml_content = CCommon::StrToUnicode(xml_str.c_str()); 23 } 24 CSimpleXML()25CSimpleXML::CSimpleXML() 26 { 27 } 28 29 ~CSimpleXML()30CSimpleXML::~CSimpleXML() 31 { 32 } 33 GetNode(const wchar_t * node,const wchar_t * parent) const34wstring CSimpleXML::GetNode(const wchar_t * node, const wchar_t * parent) const 35 { 36 wstring node_content = _GetNode(parent, m_xml_content); 37 return _GetNode(node, node_content); 38 } 39 GetNode(const wchar_t * node) const40wstring CSimpleXML::GetNode(const wchar_t * node) const 41 { 42 return _GetNode(node, m_xml_content); 43 } 44 _GetNode(const wchar_t * node,const wstring & content)45wstring CSimpleXML::_GetNode(const wchar_t * node, const wstring & content) 46 { 47 wstring result; 48 wstring node_start{ L'<' }; 49 wstring node_end{ L'<' }; 50 node_start += node; 51 node_start += L'>'; 52 node_end += L'/'; 53 node_end += node; 54 node_end += L'>'; 55 56 size_t index_start, index_end; 57 index_start = content.find(node_start); 58 index_end = content.find(node_end); 59 if (index_start == wstring::npos || index_end == wstring::npos) 60 return wstring(); 61 62 result = content.substr(index_start + node_start.size(), index_end - index_start - node_start.size()); 63 return result; 64 } 65