KML结构清晰,起初用QXmlStreamReader(之前一直没使用过)解析,花了几小时没搞定,真费劲,后来改用pugixml,10分钟搞定。
#include "./pugixml/pugixml.hpp"
void ParsePlacemark(pugi::xml_node node)
{
/*
<Placemark>
<name>A0001.JPG</name>
<visibility>1</visibility>
<Style>
<IconStyle>
<color>ffffffff</color>
<scale>1</scale>
<Icon>
<href>ico_path</href>
</Icon>
</IconStyle>
<LabelStyle>
<color>ffffffff</color>
<scale>1</scale>
</LabelStyle>
</Style>
<Point>
<altitudeMode>clampToGround</altitudeMode>
<coordinates>104.45402038920673,30.29919938150362,387.29788757221144</coordinates>
</Point>
</Placemark>
*/
pugi::xml_node nodeChild = node.first_child();
while (nodeChild)
{
if (nodeChild.name() == QStringLiteral("name"))
{
qDebug() << "name" << ": " << nodeChild.text().as_string();
}
else if (nodeChild.name() == QStringLiteral("visibility"))
{
qDebug() << "visibility" << ": " << nodeChild.text().as_string();
}
else if (nodeChild.name() == QStringLiteral("Style"))
{
qDebug() << "Style" << ": " << nodeChild.text().as_string();
}
else if (nodeChild.name() == QStringLiteral("Point"))
{
pugi::xml_node nodeChildSub = nodeChild.first_child();
while (nodeChildSub)
{
if (nodeChildSub.name() == QStringLiteral("altitudeMode"))
{
qDebug() << "altitudeMode" << ": " << nodeChildSub.text().as_string();
}
else if (nodeChildSub.name() == QStringLiteral("coordinates"))
{
qDebug() << "coordinates" << ": " << nodeChildSub.text().as_string();
}
nodeChildSub = nodeChildSub.first_child();
}
}
nodeChild = nodeChild.next_sibling();
}
}
void ParseDocument(pugi::xml_node node)
{
pugi::xml_node nodeChild = node.first_child();
while (nodeChild)
{
if (nodeChild.name() == QStringLiteral("Document"))
{
ParseDocument(nodeChild);
}
else if (nodeChild.name() == QStringLiteral("Placemark"))
{
ParsePlacemark(nodeChild);
}
nodeChild = nodeChild.next_sibling();
}
}
int main(int argc, char *argv[])
{
pugi::xml_document docKml;
if (docKml.load_file(QString("./data/中国行政区划.kml").toStdWString().c_str()))
{
docKml.root().next_sibling();
pugi::xml_node node = docKml.root().first_child();
while (node)
{
std::string name = node.name();
if (node.name() == QStringLiteral("kml"))
{
pugi::xml_node nodeChild = node.first_child();
while (nodeChild)
{
if (nodeChild.name() == QStringLiteral("Document"))
{
ParseDocument(nodeChild);
}
nodeChild = nodeChild.next_sibling();
}
}
node = node.next_sibling();
}
}
return 1;
}