QT新手,被卡主了,求赐教xml文件问题。
有一个XML文件内容如下:
<index>
<sub>
<AA>111111</AA>
<BB>222222</BB>
</sub>
<sub>
<AA>33333</AA>
<BB>4444</BB>
</sub>
</index>
我要追加一个sub节点进去,用 QDomElement root=doc.documentElement()获得xml的index跟节点(doc是读出的xml文件的QDomDocument类对象),然后用root.appendChild(Sms)添加一个节点,但是运行时都是说一个空节点无法添加子节点,本人以前没怎么接触过xml,还请求教怎么添加一个追加一个sub子节点进去呢?谢谢!
[解决办法]
#include <QFile>#include <QTextStream>#include <QDomDocument>#include <QDomElement>#include <QDomText>int main( int argc, char **argv ){ QFile inFile( "simple.xml" ); if( !inFile.open( QIODevice::ReadOnly | QIODevice::Text ) ) { qDebug( "Failed to open file for reading." ); return 0; } QDomDocument document; if( !document.setContent( &inFile ) ) { qDebug( "Failed to parse the file into a DOM tree." ); inFile.close(); return 0; } inFile.close(); QDomElement documentElement = document.documentElement(); QDomNodeList elements = documentElement.elementsByTagName( "bar" ); if( elements.size() == 0 ) { QDomElement bar = document.createElement( "bar" ); documentElement.insertBefore( bar, QDomNode() ); } else if( elements.size() == 1 ) { QDomElement bar = elements.at(0).toElement(); QDomElement baz = document.createElement( "baz" ); baz.setAttribute( "count", QString::number( bar.elementsByTagName( "baz" ).size() + 1 ) ); bar.appendChild( baz ); } QFile outFile( "simple-modified.xml" ); if( !outFile.open( QIODevice::WriteOnly | QIODevice::Text ) ) { qDebug( "Failed to open file for writing." ); return 0; } QTextStream stream( &outFile ); stream << document.toString(); outFile.close(); return 0;}