Read xml from Resouces folder, and convert to array/dictionary

Create a XML file with name “DB.xml”, and put into “Resources” folder.

<root>
	<item>
		<id>1</id>
		<period>0,2</period>
		<name>car1</name>
		<speed>120km/h</speed>
	</item>
	<item>
		<id>2</id>
		<period>0,1</period>
		<name>car2</name>
		<speed>122km/h</speed>
	</item>
	<item>
		<id>3</id>
		<period>3</period>
		<name>car3</name>
		<speed>123km/h</speed>
	</item>
	<item>
		<id>4</id>
		<period>2,4</period>
		<name>car4</name>
		<speed>110km/h</speed>
	</item>
	<item>
		<id>5</id>
		<period>1,2,3</period>
		<name>car5</name>
		<speed>140km/h</speed>
	</item>
	<item>
		<id>6</id>
		<period>0,4</period>
		<name>car6</name>
		<speed>130km/h</speed>
	</item>
</root>

Switch to Unity

using System.Xml.Linq;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
 
Void Start(){
  TextAsset myXML = (TextAsset) Resources.Load("DB");
  var dbArr = XDocument.Load(new System.IO.StringReader(myXML.text)).Root.Elements().
Select(y => y.Elements().ToDictionary(x => x.Name, x => x.Value)).ToArray();
  Debug.Log("try to get first item's name:"+dbArr[0]["name"]);
}

回复 (0)

› 尚无评论。

引用通告 (0)

› 尚无引用通告。