如何在不使用 C/C++ (Windows) 中的 DOM 的情况下检查 XML 文件中的标记

How to check for a tag in an XML File without using DOM in C / C++ (Windows)?

本文关键字:情况下 DOM 中的 检查 XML 文件 Windows C++      更新时间:2023-10-16

我想读取 system32\Tasks 文件夹中的 XML 文件并检查文件中是否存在标签。我只需要检查 XML 文件中的标签。而且该文件不一定必须与项目文件位于同一目录中。 void listdirs(WCHAR *dir, WCHAR *mask) { WCHAR fspec1[1000], fname[1000]; WIN32_FIND_DATAW DTA = {0}; 句柄 hDta = 空; DWORD dLastError = 0; LPCWSTR fspec = NULL;

swprintf(fspec1, 100, L"%ws%ws", dir, mask);
fspec = reinterpret_cast<LPCWSTR>(fspec1);
if ((hDta = FindFirstFileW(fspec, &dta)) == INVALID_HANDLE_VALUE) {
    dLastError = GetLastError();
  printf("The error : %sn", strerror(dLastError));

}
else {
    do {

        if ((dta.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
        {   
if(wcscmp(dta.cFileName, L".") !=0 &&  wcscmp(dta.cFileName, L"..") != 0)
   {    
      //Insert code snippet here to check whether the file has <Date> tag        
          or not
swprintf(fname, 100,  L"%ws%ws%ws", dir, dta.cFileName, L"\");
listdirs(fname, mask);
}
}
else
{
            count++;
            printf("%wsn", dta.cFileName);
            printf("Count is : %dn", count);
}
    } while (FindNextFileW(hDta, &dta));
    FindClose(hDta);
}
}

我尝试使用TinyXml,但我很难理解它,因为我对DOM一无所知,并且更喜欢更简单的选择

如果您只检查标签,则可以使用正则表达式:


#include <iostream>
#include <string>
#include <regex>
bool TagExists(const std::string& input,const std::string& tag)
{
    std::regex rgx(std::format("<{}>", tag));
    std::smatch match;
    if (std::regex_search(input.begin(), input.end(), match, rgx))
        return true;
    else
        return false;
}

但不要忘记,这并不控制 XML 是否有效或标记是否已关闭。它只检查正则表达式。

如果我将其注入到您的代码中,它将是这样的:

swprintf(fspec1, 100, L"%ws%ws", dir, mask);
fspec = reinterpret_cast<LPCWSTR>(fspec1);
if ((hDta = FindFirstFileW(fspec, &dta)) == INVALID_HANDLE_VALUE) {
    dLastError = GetLastError();
  printf("The error : %sn", strerror(dLastError));

}
else {
    do {

        if ((dta.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
        {   
if(wcscmp(dta.cFileName, L".") !=0 &&  wcscmp(dta.cFileName, L"..") != 0)
   {    
      //Insert code snippet here to check whether the file has <Date> tag        
          or not
     
      swprintf(fname, 100,  L"%ws%ws%ws", dir, dta.cFileName, L"\");
      listdirs(fname, mask);
    
      std::ifstream t(fname);
      std::string str((std::istreambuf_iterator<char>(t)),
                 std::istreambuf_iterator<char>());
      bool st=TagExists(str, "Date");
      // make whatever you want with this information. I just printed
      printf("Tag "Date" is %s exists in %wsn", st? "":"not", dta.cFileName);
   }
}
else
{
            count++;
            printf("%wsn", dta.cFileName);
            printf("Count is : %dn", count);
}
    } while (FindNextFileW(hDta, &dta));
    FindClose(hDta);
}
}