例 ノード名を取得する
ここではQDomNodeクラスの以下のメソッドの例を示します
nodeName() |
ノード名を取得する |
namespaceURI() |
名前空間URIを取得する |
prefix() |
接頭辞を取得する |
localName() |
ローカル名を取得する |
XMLファイル (例では"C:\\example.xml"にファイルが存在)
<root xmlns="http://www.w3.org/default">
<cname:table xmlns:cname="http://www.w3.org/color_name">
<cname:tr>
<cname:td>red</cname:td>
</cname:tr>
</cname:table>
<ccode:table xmlns:ccode="http://www.w3.org/color_code">
<ccode:tr>
<ccode:td>#FF0000</ccode:td>
</ccode:tr>
</ccode:table>
<table>
<tr>
<td>sushi</td>
</tr>
</table>
</root>
コード
XML関連のクラスを使用する場合はプロジェクトのproファイルに QT += xml を追加する必要があります
#include <QCoreApplication>
#include <QtXml>
void showTree(QDomNode parent );
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QDomDocument doc("mydocument");
QFile file("C:\\example.xml");
//setContent()の第二引数がtrueでないとXMLで名前空間を使用していても解析されません
if ( !doc.setContent( &file, true ) )
{
qDebug() << "error occurred.";
file.close();
return a.exec();
}
file.close();
showTree ( doc.ownerDocument () );
return a.exec();
}
void showTree(QDomNode parent)
{
for( QDomNode node = parent.firstChild (); !node.isNull (); node = node.nextSibling () )
{
qDebug() << " nodeName: " << node.nodeName ()
<< " namespaceURI: " << node.namespaceURI ()
<< " prefix: " << node.prefix ()
<< " localName: " << node.localName ();
showTree( node );
}
}
結果
参考リンク
最終更新:2014年05月28日 21:49