How to get last node of XML file in QT?

191 Views Asked by At

In my current project i am parsing the XML file using QDomDocument class. My XML file look like bellow:

<string>
<Data>
    <Details>
        <Content>
            <Name>James</Name>
            <DOB>30/09/1980</DOB>
            <MobileNo/>
            <Address>USA</Address>
        </Content>
        <Content>
            <Name>Ram</Name>
            <DOB>30/09/1995</DOB>
            <MobileNo>9876543210</MobileNo>
            <Address>India</Address>
        </Content>
        <Content>
            <Name>Jack</Name>
            <DOB/>
            <MobileNo>9876543210</MobileNo>
            <Address>UK</Address>
        </Content>
    </Details>
</Data>

In XML file number of <Content> tags. How I print last <Content> tag with its all data with respective tag name. My output will like:

<Content>
      <Name>Jack</Name>
      <DOB/>
      <MobileNo>9876543210</MobileNo>
      <Address>UK</Address>
</Content>

Can anyone give me some sample code for this that work me in QT(C++)

1

There are 1 best solutions below

1
On

I haven't actually tested this so there might be some mistake in the code. However looking at the Qt documentation here, I believe you should be able to achieve your goal by doing something like this:

QDomDocument doc = // ...
QDomElement root = doc.firstChildElement("string");
QDomElement elt = root.firstChildElement("Data")
        .firstChildElement("Details")
        .lastChildElement("Content");

QDomNamedNodeMap nma = elt.attributes();
int nmaLength = nma.length();
for (int i=0; i<nmaLength; ++i) {
    QDomAttr attr = nma.item(i).toAttr();
    qDebug() << attr.name().toLocal8Bit().constData() << ": " 
            << attr.value().toLocal8Bit().constData();
}