例 ノード名を取得する

例 ノード名を取得する

ここでは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 );
	}
}
 

結果

nodeName() namespaceURI() prefix() localName()
"root" "http://www.w3.org/default" "" "root"
"cname:table" "http://www.w3.org/color_name" "cname" "table"
"cname:tr" "http://www.w3.org/color_name" "cname" "tr"
"cname:td" "http://www.w3.org/color_name" "cname" "td"
"#text" "" "" ""
"ccode:table" "http://www.w3.org/color_code" "ccode" "table"
"ccode:tr" "http://www.w3.org/color_code" "ccode" "tr"
"ccode:td" "http://www.w3.org/color_code" "ccode" "td"
"#text" "" "" ""
"table" "http://www.w3.org/default" "" "table"
"tr" "http://www.w3.org/default" "" "tr"
"td" "http://www.w3.org/default" "" "td"
"#text" "" "" ""

参考リンク

タグ:

+ タグ編集
  • タグ:

このサイトはreCAPTCHAによって保護されており、Googleの プライバシーポリシー利用規約 が適用されます。

最終更新:2014年05月28日 21:49