はかせのラボ

私の頭の中を書いていく雑記ブログです

boost boost使ってXMLを読んでみた話

あいさつ

どうも、はかせです。
今回は前回入れたboostを使ってXMLを読んでみた話です。

boostを使ってXMLを読む

boostでXMLを読むのは以下のような手順でやります。
・boost::property_tree::ptree を宣言する
・boost::property_tree::read_xmlに読むXMLのパスとptreeを渡して実行
・ptreeの中身をバラシて自分のプログラムに落とす

ではそんな感じのコードを見ていきましょう。

#pragma once
#include <iostream>
#include <string>
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/lexical_cast.hpp>

class BoostTest
{
public:
	BoostTest();
	~BoostTest() {};
	void show_xml(boost::property_tree::ptree &pt, int indent = 0);
};
#include "pch.h"
#include "BoostTest.h"

BoostTest::BoostTest()
{
	boost::property_tree::ptree pt;
	boost::property_tree::read_xml("TitleSceneData.xml", pt);

	try 
	{
		show_xml(pt);
	}
	catch (std::exception const &ex) 
	{
		std::cout << "xml parse error." << std::endl;
	}
}

void BoostTest::show_xml(boost::property_tree::ptree &pt, int indent) 
{
	for (auto &it : pt) 
	{
		if (it.first == "<xmlattr>") continue;
		std::string attr;
		bool no_child = true;
		for (auto &itt : it.second.get_child("")) 
		{
			if (itt.first == "<xmlattr>") 
			{
				for (auto &ittt : itt.second.get_child("")) 
				{
					attr += " " + ittt.first + "=\"" + boost::lexical_cast<std::string>(ittt.second.data()) + "\"";
				}
				continue;
			}
			no_child = false;
		}
		for (int i = 0; i < indent; ++i) 
		{
			std::cout << "\t";
		}
		std::cout << "<" << it.first << attr << ">";
		if (no_child) 
		{
			std::cout << it.second.data();
		}
		else 
		{
			std::cout << std::endl;
			show_xml(it.second, indent + 1);
			for (int i = 0; i < indent; ++i) 
			{
				std::cout << "\t";
			}
		}
		std::cout << "</" << it.first << ">" << std::endl;
	}
}

BoostTestのコンストラクタでptreeの宣言とread_xmlの実行を行い、
show_xmlでptreeをバラシています。

まだそこまで深く理解はできていないですが、
boostのXML解析はもう作りきった構造体に
読み込んだ値を当てはめていってるっぽいです。
(詳しいことはもっとしっかり読み込んで理解出来たら書きます)

あとがき

今回はboostのXML解析を使ってみた話でした。

今私は完全にこれですw
f:id:hakase0274:20190714231850p:plain

ツールとかってやっぱ難しいですねー
色んな人が色んな風に使うから
それに備えてあーだこーだやってるからでしょうけど、
よくわからんですw

ゲーム本体を作るだけならこのままboostに頼ってしまうのもいいんですが、
勉強目的でやるなら可能な限り自作でやり切りたい気持ちがあるんですよねー
(先にデータ管理だけ済まして、あとからパーサー自作とかもありかな)

就活は終わりましたが、
その間放置してたり後回しにしてたことが一気に押し寄せてきてて、
結局プログラミング勉強に使える時間はあまり変わってないですw
その中で無理しない程度に頑張っていきたいと思います。
それでは今回はこの辺でノシ

参考

qiita.com