我正在尝试使用QXmlStreamReader(Qt 5.5.1)在C ++中解析xml文件。我正在使用XML文件将数字键映射到相应的图像文件。我已经将其与简单的XML文件一起使用,例如:
<?xml version="1.0" encoding="UTF-8"?>
<images>
<group1>
<image key="1" value="image1_group1.png"/>
<image key="2" value="image2_group1.png"/>
</group1>
<group2>
<image key="1" value="image1_group2.png"/>
<image key="2" value="image2_group2.png"/>
</group2>
</images>
使用以下代码:
#include <QFile>
xml_image_mapper::xml_image_mapper(QObject* p_parent_ptr)
{
QFile file("myfile.xml");
file.open(QFile::ReadOnly | QFile::Text);
QXmlStreamReader stream_reader(&file);
stream_reader.readNextStartElement();
while (stream_reader.readNextStartElement())
{
auto* inner_map_ptr = new QMap<quint32, QString>();
m_image_map.insert(stream_reader.name().toString(), inner_map_ptr);
parse_xml(stream_reader, *inner_map_ptr);
}
}
void xml_image_mapper::parse_xml(QXmlStreamReader& stream_reader, QMap<quint32, QString>& p_map)
{
while (stream_reader.readNextStartElement())
{
static const QString key_name = "key";
static const QString value_name = "value";
quint32 key;
QString value;
foreach (const QXmlStreamAttribute attribute, stream_reader.attributes())
{
if (key_name == attribute.name())
key = attribute.value().toInt();
else if (value_name == attribute.name())
value = attribute.value().toString();
p_map.insert(key, value);
}
stream_reader.skipCurrentElement();
}
}
对于上面显示的简单XML,此代码正确地创建了从数字键到文件名的映射,但是对于包含引用的XML文件无效,例如:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE doc [
<!ENTITY group1 SYSTEM "group1.xml">
<!ENTITY group2 SYSTEM "group2.xml">
]>
<images>
<group1>
&group1;
</group1>
<group2>
&group2;
</group2>
</images>
group1.xml的读取内容:
<?xml version="1.0" encoding="UTF-8"?>
<image key="1" value="image1_group1.png"/>
<image key="2" value="image2_group1.png"/>
和group2.xml读取:
<?xml version="1.0" encoding="UTF-8"?>
<image key="1" value="image1_group2.png"/>
<image key="2" value="image2_group2.png"/>
是否可以使用QXmlStreamReader解析XML文件以及对其他XML文件的引用?