﻿using System;
using System.Xml;

namespace Rayman
{
	public class XmlReader
	{
		private XmlDocument _xml;
		private XmlNode _rootNode;

		public XmlReader(){}

		public XmlNodeList rootChildNodes
		{
			get { return _rootNode.ChildNodes; }
		}

		public bool Parse(string content)
		{
			_xml = new XmlDocument();
			_xml.LoadXml(content);

			return true;
		}

		public void ReadRootNode(string rootStr = "Catalog")
		{
			_rootNode = _xml.SelectSingleNode(rootStr);
		}


		//从root中寻找一个child node, 然后从node中读取一个属性
		//这里用ref的原因是因为, 如果在node中找不到这个属性, 就不改变t的值
		public bool TryReadChildNodeAttr(XmlElement parent, string childNodeName, string attrName, ref int t)
		{
			XmlElement node =  parent.SelectSingleNode(childNodeName) as XmlElement;
			if (node == null)return false;

			string v = node.GetAttribute(attrName);
			return Int32.TryParse(v, out t);
		}

		public bool TryReadChildNodeAttr(XmlElement parent, string childNodeName, string attrName, ref float t)
		{
			XmlElement node =  parent.SelectSingleNode(childNodeName) as XmlElement;
			if (node == null)return false;

			string v = node.GetAttribute(attrName);
			return float.TryParse(v, out t);
		}

		public bool TryReadChildNodeAttr(XmlElement parent, string childNodeName, string attrName, ref string t)
		{
			XmlElement node =  parent.SelectSingleNode(childNodeName) as XmlElement;
			if (node == null)return false;

			t = node.GetAttribute(attrName);
			return true;
		}

		public void Close()
		{
			_xml = null;
		}
	}
}