How to get line number from XML file when using with QDomDocument?
-
Maybe you could check this
int QDomNode::lineNumber() const
For nodes created by QDomDocument::setContent(), this function returns the line number in the XML document where the node was parsed. Otherwise, -1 is returned.
This function was introduced in Qt 4.1. -
@Bonnie It is not useful. It will only show parsing error. like this example, if <string> tag is not ended with </string>.
<string> <Data> <Name>abc</Name> <Number>123</Number> <Address>kjl</Address> </Data> <Data> <Name>zutr</Name> <Number>897</Number> <Address>bgfs</Address> </Data> <string>
-
@nn26 I think you've misunderstood something.
This is not theint *errorLine
inQDomDocument::setContent
function.
You see? when you have parse errors, you can't get a valid QDomNode...
I've tried your xml text in the top post, this function works well.QDomDocument doc; if(doc.setContent(text.toUtf8())) { auto element = doc.documentElement().firstChildElement(); qDebug() << element.tagName() << element.lineNumber() << element.columnNumber() << endl; }
the output is
"Data" 2 14
-
@Bonnie thank you for the answer.
doc.documentElement().firstChildElement()
this will give output of <Data> in line 2, but how to get line number of another <Data> tag when working in loop?
```
QDomDocument doc;
QDomElement root = doc.documentElement();for example when working with loop after getting root from above code,
QDomNode node = root.firstChild();
while (!node.isNull()) { QDomElement element = node.toElement(); **qDebug()<< root.toElement().firstChildElement().lineNumber();** .... .... node = node.nextSibling(); }
so, Here root.toElement().firstChildElement().lineNumber() is giving correct line number in first iteration but for other iteration it is repeating same line number which is not correct.
-
@nn26 Seems your question is how to iterate.
auto element = doc.documentElement().firstChildElement(); while(!element.isNull()) { qDebug() << element.tagName() << element.lineNumber() << endl; element = element.nextSiblingElement(); }
Here you can get all of the
Data
s -