我对在C++中使用XML感到很陌生,并且试图解析要下载的文件列表。
我正在使用的XML文件是通过PHP生成的,看起来像这样:
<?xml version="1.0"?>
<FileList>
<File Name="xxx" Path="xxx" MD5="xxx" SHA1="xxx"/>
</FileList>
以下是我在C++中使用的代码,这些代码是我通过一些在线教程(包含在某些全局函数中)提出的:
tinyxml2::XMLDocument doc;
doc.LoadFile("file_listing.xml");
tinyxml2::XMLNode* pRoot = doc.FirstChild();
tinyxml2::XMLElement* pElement = pRoot->FirstChildElement("FileList");
if (pRoot == nullptr)
{
QString text = QString::fromLocal8Bit("Error text in french");
//other stuff
}
else
{
tinyxml2::XMLElement* pListElement = pElement->FirstChildElement("File");
while (pListElement != nullptr)
{
QString pathAttr = QString::fromStdString(pListElement->Attribute("Path"));
QString md5Attr = QString:: fromStdString(pListElement->Attribute("MD5"));
QString sha1Attr = QString::fromStdString(pListElement->Attribute("SHA1"));
QString currentPath = pathAttr.remove("path");
QString currentMd5 = this->fileChecksum(currentPath, QCryptographicHash::Md5);
QString currentSha1 = this->fileChecksum(currentPath, QCryptographicHash::Sha1);
QFile currentFile(currentPath);
if (md5Attr != currentMd5 || sha1Attr != currentSha1 || !currentFile.exists())
{
QString url = "url" + currentPath;
this->downloadFile(url);
}
pListElement = pListElement->NextSiblingElement("File");
}
问题是,我在下一行收到类似“访问冲突,这是nullptr”的错误:
tinyxml2::XMLElement* pListElement = pElement->FirstChildElement("File");
由于我在编码方面还远非专业人士,而且我已经在互联网上上下搜索,所以我希望这里的人可以为我提供一些指导。
祝大家有美好的一天。
最佳答案
我不知道您是否有C++ 17,但是可以通过使用auto*
和if-init-expressions
(或依靠可以将指针隐式转换为 bool(boolean) 值的事实)来消除很多干扰。
代码的主要问题是您没有使用XMLElement*
,而是使用了XMLNode
。函数tinyxml2::XMLDocument::RootElement()
自动为您获取最顶层的元素。
因为您在顶部有一个xml声明,所以FirstChild
返回该声明……它没有任何子代,因此其余代码将失败。
通过使用RootElement
,tinyxml知道跳过任何领先的非元素节点(注释,文档类型等),而是为您提供<FileList>
。
tinyxml2::XMLDocument doc;
auto err = doc.LoadFile("file_listing.xml");
if(err != tinyxml2::XML_SUCCESS) {
//Could not load file. Handle appropriately.
} else {
if(auto* pRoot = doc.RootElement(); pRoot == nullptr) {
QString text = QString::fromLocal8Bit("Error text in french");
//other stuff
} else {
for(auto* pListElement = pRoot->FirstChildElement("File");
pListElement != nullptr;
pListElement = pListElement->NextSiblingElement("File"))
{
QString pathAttr = QString::fromStdString(pListElement->Attribute("Path"));
QString md5Attr = QString:: fromStdString(pListElement->Attribute("MD5"));
QString sha1Attr = QString::fromStdString(pListElement->Attribute("SHA1"));
QString currentPath = pathAttr.remove("path");
QString currentMd5 = this->fileChecksum(currentPath, QCryptographicHash::Md5);
QString currentSha1 = this->fileChecksum(currentPath, QCryptographicHash::Sha1);
QFile currentFile(currentPath);
if(md5Attr != currentMd5 || sha1Attr != currentSha1 || !currentFile.exists()) {
QString url = "url" + currentPath;
this->downloadFile(url);
}
}
}
}
关于c++ - 使用TinyXML2在C++中读取XML文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62159742/