PDA

View Full Version : How do I get tag names of all child elements for an XML element



rawfool
6th June 2013, 14:25
Considering this XML, I'm able to get the data under some tags, but under one element, there might be a few child elements, and the number of the may change. So is there any way I can get all the child tags & data associated with it ?


<metadata xmlns="http://www.scaprepo.com/SCAPRepoWebService/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.scaprepo.com/SCAPRepoWebService/schema http://www.scaprepo.com/SCAPRepoWebService/schema/metadata.xsd">
<entities>
<entity>
<id>cpe:/a:microsoft:ie:9</id>
<uri>http://www.scaprepo.com/control.jsp?command=viewXML&amp;id=cpe:/a:microsoft:ie:9</uri>
<desc>Microsoft Internet Explorer 9</desc>
<created-date>2011-06-27</created-date>
<modified-date>2013-05-24</modified-date>
<properties>
<property key="product">ie</property>
<property key="vendor">microsoft</property>
<property key="check">oval:org.secpod.oval:def:4</property>
</properties>
</entity>
</entities>
</metadata>

Here under properties I need to get the all the key names & data associated with each key.
For others, since I know the tags before-hand, I'll get the data as shown below.

QDomDocument domDoc;
domDoc.setContent(xmlFileData);
QDomNodeList id = domDoc.elementsByTagName("id");
QDomNodeList uri = domDoc.elementsByTagName("uri");
QDomNodeList desc = domDoc.elementsByTagName("desc");
QDomNodeList crDate = domDoc.elementsByTagName("created-date");
QDomNodeList mdDate = domDoc.elementsByTagName("modified-date");

And with the below shown method, I'm able to get data for all the child tags with key values, but I need to know a way to find key names also.


QDomNodeList properties= domDoc.elementsByTagName("properties").at(0).childNodes();

for(int i = 0; i < product.count(); i++)
{
qDebug() << "\nElement-" + QString::number(i) + ": " << properties.at(i).toElement().text() << endl;
}
Kindly help me with getting tag/key values & data under properties tag. Thank you.

Lykurg
7th June 2013, 06:06
Ok, at a time you will have the properties tag:

QDomElement properties = /*...*/;
for(QDomElement property = properties.firstChildElement("property"); !property.isNull(); property = property.nextSiblingElement("property"))
{
// here you can work with property
}

Also instead of get the list of all tags (elementsByTagName) better walk throug the DOM with loops as shown above.