1
我想解析一個使用QXmlQuery(Qt 5.0)的gpx文件。Qt XmlQuery子查詢屬性
的想法是收集所有trkpt元素,然後子查詢的每個元素,以提取緯度,經度,海拔...
的問題是,它似乎無法識別屬性名稱,因爲這代碼工作:
query.setQuery
(
"declare default element namespace \"http://www.topografix.com/GPX/1/1\";"
"declare variable $gpxFile external;"
"doc($gpxFile)//trkpt"
);
if(query.isValid())
{
QXmlResultItems trkpts;
query.evaluateTo(&trkpts);
for(QXmlItem trkpt = trkpts.next(); !trkpt.isNull(); trkpt = trkpts.next())
{
QXmlQuery childQuery;
QStringList res;
childQuery.setFocus(trkpt);
childQuery.setQuery
(
"@*/string()"
); // <------------------------- this prints out all the attributes
childQuery.evaluateTo(&res);
qDebug() << res << "\n";
}
}
而這一次沒有:
// ... same code as above
childQuery.setQuery
(
"@lat/string()"
); // <------------------------- this prints out only a \n
// ... same code as above
什麼是錯的任何想法?
請注意,如果我試圖收集使用「外」查詢所有@lat屬性,它按預期工作:
query.setQuery
(
"declare default element namespace \"http://www.topografix.com/GPX/1/1\";"
"declare variable $gpxFile external;"
"doc($gpxFile)//trkpt/@lat/string()"
);
編輯
這是一個GPX樣本文件:
<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<gpx
version="1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.topografix.com/GPX/1/0"
xmlns:topografix="http://www.topografix.com/GPX/Private/TopoGrafix/0/2"
xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.topografix.com/GPX/Private/TopoGrafix/0/2 http://www.topografix.com/GPX/Private/TopoGrafix/0/2/topografix.xsd">
<trk>
<name>My track</name>
<desc>My track description</desc>
<trkseg>
<trkpt lat="38.919839863" lon="-121.020112049">
<ele>265.447754</ele>
<time>2003-02-05T18:19:20Z</time>
</trkpt>
<trkpt lat="38.919796947" lon="-121.020240795">
<ele>264.967041</ele>
<time>2003-02-05T18:19:20Z</time>
</trkpt>
<trkpt lat="38.919861320" lon="-121.020498287">
<ele>263.044434</ele>
<time>2003-02-05T18:19:20Z</time>
</trkpt>
<trkpt lat="38.919990066" lon="-121.020798694">
<ele>263.525146</ele>
<time>2003-02-05T18:19:20Z</time>
</trkpt>
</trkseg>
</trk>
</gpx>
編輯
我通過使用QDomDocument而不是QXmlQuery找到了解決此問題的解決方法。 結果看起來像下面的代碼(的所有錯誤檢查簡潔的緣故刪除):
QFile file = ("mytrack.gpx");
file.open(QIODevice::ReadOnly);
QDomDocument doc("mydoc");
doc.setContent(&file);
QDomElement root = doc.documentElement();
QDomNodeList trkpts = root.elementsByTagName("trkpt");
for(int i = 0; i < trkpts.length(); i++)
{
QDomElement e = trkpts.at(i).toElement();
QString latitude = e.attribute("lat");
QString longitude = e.attribute("lon");
QDomNodeList elevation_list = e.elementsByTagName("ele");
QString elevation = elevation_list.at(0).toElement().text();
// ... and so on
}
我想用QXmlQuery找到一個解決這個問題,但與此同時,這只是工作。
我也曾想過一個命名空間問題,但您提出的解決方案的許多變體似乎並不奏效! 我按照您的建議添加數據示例,希望它有幫助。 – Cristiano