How can I manage that my XML reader, searching for attributes with a special parent element?
e.g. my XML file:
<section name="aPoly">
<attribute key="id" type="int">1</attribute>
<attribute key="label" type="String">2</attribute>
<section name="graphic">
<attribute key="x" type="double">780.0</attribute>
<attribute key="y" type="double">240.0</attribute>
<attribute key="w" type="double">78.0</attribute>
<attribute key="h" type="double">78.0</attribute>
</section>
</section>
...
...
<section name="line">
<attribute key="source" type="int">0</attribute>
<attribute key="target" type="int">4</attribute>
<section name="graphic">
<attribute key="fill" type="String">#000000</attribute>
<section name="poly">
<section name="pt">
<attribute key="x" type="double">377.0</attribute>
<attribute key="y" type="double">240.0</attribute>
</section>
<section name="pt">
<attribute key="x" type="double">570.0</attribute>
<attribute key="y" type="double">240.0</attribute>
</section>
<section name="pt">
<attribute key="x" type="double">570.0</attribute>
<attribute key="y" type="double">330.0</attribute>
</section>
</section>
</section>
</section>
There are multiple attributes with key = "x"
. I want to save the x values of section name="aPoly"
in one array and the x values of section name="line"
into another array.
I am searching for attributes and save it to a QVector. (Search all X attributes).
QDomElement root = document.documentElement();
QDomNodeList key = root.elementsByTagName("attribute");
for(int i = 0; i < key.count(); i++)
{
QDomNode keynode = key.at(i);
if(keynode.isElement())
{
QDomElement att = keynode.toElement();
if (att.attribute("key") == "x"){
xarray.push_back(att.text());
}else if (att.attribute("key") =="y") {
yarray.push_back(att.text());
}...
What can I change to achieve this?
Edit:
Why he dont fill my array? Its always empty? Where is my mistake?
QXmlQuery query;
if (query.setFocus(&file))
{
query.setQuery(QString("section/section/section[@name='aPoly']/section/attribute[@key='x']"));
if (query.isValid())
{
QString result;
query.evaluateTo(&result);
QDomDocument dom;
dom.setContent(QString("<Data>%1</Data>").arg(result));
QDomNodeList children = dom.documentElement().childNodes();
for (int i = 0; i < children.count(); i++)
{
QDomNode nod = children.at(i);
if(nod.isElement())
{
QDomElement art = nod.toElement();
Newarray.push_back(art.text());
}
}
}
}
qDebug() << "\r\nNewArray : " <<QList<QString>::fromVector(Newarray);
You can use
XQuery
for this. XPath similar to following can be used for your purpose assumingsection
elements are inside asections
element and it is the root of your xml document.Eg.