private PlistObjectBase LoadFromNode(XmlReader reader) { Debug.Assert(reader.NodeType == XmlNodeType.Element); bool isEmpty = reader.IsEmptyElement; switch (reader.LocalName) { case "dict": var dict = new PlistDictionary(true); if (!isEmpty) { if (reader.ReadToDescendant("key")) { dict = LoadDictionaryContents(reader, dict); } reader.ReadEndElement(); } return(dict); case "array": if (isEmpty) { return(new PlistArray()); } //advance to first node reader.ReadStartElement(); while (reader.Read() && reader.NodeType != XmlNodeType.Element) { ; } // HACK: plist data in iPods is not even valid in some cases! Way to go Apple! // This hack checks to see if they really meant for this array to be a dict. if (reader.LocalName == "key") { var ret = LoadDictionaryContents(reader, new PlistDictionary(true)); reader.ReadEndElement(); return(ret); } var arr = new PlistArray(); do { if (reader.NodeType == XmlNodeType.Element) { var val = LoadFromNode(reader); if (val != null) { arr.Add(val); } } } while (reader.Read() && reader.NodeType != XmlNodeType.EndElement); reader.ReadEndElement(); return(arr); case "string": return(new PlistString(reader.ReadElementContentAsString())); case "integer": return(new PlistInteger(reader.ReadElementContentAsInt())); case "real": return(new PlistReal(reader.ReadElementContentAsFloat())); case "false": reader.ReadStartElement(); if (!isEmpty) { reader.ReadEndElement(); } return(new PlistBoolean(false)); case "true": reader.ReadStartElement(); if (!isEmpty) { reader.ReadEndElement(); } return(new PlistBoolean(true)); case "data": return(new PlistData(reader.ReadElementContentAsString())); case "date": #if NETFX_CORE return(new PlistDate(DateTime.Parse(reader.ReadElementContentAsString()))); #else return(new PlistDate(reader.ReadElementContentAsDateTime())); #endif default: throw new XmlException(String.Format("Plist Node `{0}' is not supported", reader.LocalName)); } }
protected override void ReadStartElement(XmlReader reader) { if (reader.AttributeCount != 0) { throw new XmlException("Encountered unexpected attributes on element " + reader.Name + "."); } if (String.Equals(reader.Name, "climate", StringComparison.Ordinal)) { reader.Read(); } else if (String.Equals(reader.Name, "co2concentration", StringComparison.Ordinal)) { this.CO2ConcentrationInPpm = reader.ReadElementContentAsFloat(); if ((this.CO2ConcentrationInPpm < 0.0F) || (this.CO2ConcentrationInPpm > 1E6F)) { throw new XmlException("CO₂ concentration is negative or greater than 100%."); } } else if (String.Equals(reader.Name, "databaseFile", StringComparison.Ordinal)) { this.DatabaseFile = reader.ReadElementContentAsString().Trim(); } else if (String.Equals(reader.Name, "databaseQueryFilter", StringComparison.Ordinal)) { this.DatabaseQueryFilter = reader.ReadElementContentAsString().Trim(); } else if (String.Equals(reader.Name, "defaultDatabaseTable", StringComparison.Ordinal)) { this.DefaultDatabaseTable = reader.ReadElementContentAsString().Trim(); } else if (String.Equals(reader.Name, "batchYears", StringComparison.Ordinal)) { this.BatchYears = reader.ReadElementContentAsInt(); if (this.BatchYears < 1) { throw new XmlException("Maximum number of years to load per climate table read (batchYears) is zero or negative."); } } else if (String.Equals(reader.Name, "temperatureShift", StringComparison.Ordinal)) { this.TemperatureShift = reader.ReadElementContentAsFloat(); // no restriction on value range } else if (String.Equals(reader.Name, "precipitationShift", StringComparison.Ordinal)) { this.PrecipitationMultiplier = reader.ReadElementContentAsFloat(); // no restriction on value range } else if (String.Equals(reader.Name, "randomSamplingEnabled", StringComparison.Ordinal)) { this.RandomSamplingEnabled = reader.ReadElementContentAsBoolean(); } else if (String.Equals(reader.Name, "randomSamplingList", StringComparison.Ordinal)) { this.RandomSamplingList = reader.ReadElementContentAsString().Trim(); } else { throw new XmlException("Element '" + reader.Name + "' is unknown, has unexpected attributes, or is missing expected attributes."); } }
private float XRfloat() { return(reader.ReadElementContentAsFloat()); }
public override float ReadElementContentAsFloat() { this.IsCalled = true; return(_wrappedreader.ReadElementContentAsFloat()); }
public object ReadObject(Type type) { if (serialized_object_count++ == serializer.MaxItemsInObjectGraph) { throw SerializationError(String.Format("The object graph exceeded the maximum object count '{0}' specified in the serializer", serializer.MaxItemsInObjectGraph)); } bool isNull = reader.GetAttribute("type") == "null"; switch (Type.GetTypeCode(type)) { case TypeCode.DBNull: string dbn = reader.ReadElementContentAsString(); if (dbn != String.Empty) { throw new SerializationException(String.Format("The only expected DBNull value string is '{{}}'. Tha actual input was '{0}'.", dbn)); } return(DBNull.Value); case TypeCode.String: if (isNull) { reader.ReadElementContentAsString(); return(null); } else { return(reader.ReadElementContentAsString()); } case TypeCode.Char: var c = reader.ReadElementContentAsString(); if (c.Length > 1) { throw new XmlException("Invalid JSON char"); } return(Char.Parse(c)); case TypeCode.Single: return(reader.ReadElementContentAsFloat()); case TypeCode.Double: return(reader.ReadElementContentAsDouble()); case TypeCode.Decimal: return(reader.ReadElementContentAsDecimal()); case TypeCode.Byte: case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.UInt16: int i = reader.ReadElementContentAsInt(); if (type.IsEnum) { return(Enum.ToObject(type, (object)i)); } else { return(Convert.ChangeType(i, type, null)); } case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: long l = reader.ReadElementContentAsLong(); if (type.IsEnum) { return(Enum.ToObject(type, (object)l)); } else { return(Convert.ChangeType(l, type, null)); } case TypeCode.Boolean: return(reader.ReadElementContentAsBoolean()); case TypeCode.DateTime: // it does not use ReadElementContentAsDateTime(). Different string format. var s = reader.ReadElementContentAsString(); if (s.Length < 2 || !s.StartsWith("/Date(", StringComparison.Ordinal) || !s.EndsWith(")/", StringComparison.Ordinal)) { throw new XmlException("Invalid JSON DateTime format. The value format should be '/Date(UnixTime)/'"); } return(new DateTime(1970, 1, 1).AddMilliseconds(long.Parse(s.Substring(6, s.Length - 8)))); default: if (type == typeof(Guid)) { return(new Guid(reader.ReadElementContentAsString())); } else if (type == typeof(Uri)) { if (isNull) { reader.ReadElementContentAsString(); return(null); } else { return(new Uri(reader.ReadElementContentAsString())); } } else if (type == typeof(XmlQualifiedName)) { s = reader.ReadElementContentAsString(); int idx = s.IndexOf(':'); return(idx < 0 ? new XmlQualifiedName(s) : new XmlQualifiedName(s.Substring(0, idx), s.Substring(idx + 1))); } else if (type != typeof(object)) { // strongly-typed object if (reader.IsEmptyElement) { // empty -> null array or object reader.Read(); return(null); } Type ct = GetCollectionType(type); if (ct != null) { return(DeserializeGenericCollection(type, ct)); } else { TypeMap map = GetTypeMap(type); return(map.Deserialize(this)); } } else { return(ReadInstanceDrivenObject()); } } }
protected override void ReadStartElement(XmlReader reader) { if (reader.AttributeCount != 0) { throw new XmlException("Encountered unexpected attributes on element " + reader.Name + "."); } if (String.Equals(reader.Name, "snags", StringComparison.Ordinal)) { reader.Read(); } else if (String.Equals(reader.Name, "stemC", StringComparison.Ordinal)) { this.StemCarbon = reader.ReadElementContentAsFloat(); if (this.StemCarbon < 0.0F) { throw new XmlException("Standing woody debris carbon is negative."); } } else if (String.Equals(reader.Name, "stemCN", StringComparison.Ordinal)) { this.StemCarbonNitrogenRatio = reader.ReadElementContentAsFloat(); if (this.StemCarbonNitrogenRatio < 0.0F) { throw new XmlException("Standing woody debris carbon:nitrogen ratio is negative."); } } else if (String.Equals(reader.Name, "snagsPerRU", StringComparison.Ordinal)) { this.SnagsPerResourceUnit = reader.ReadElementContentAsFloat(); if (this.SnagsPerResourceUnit < 0.0F) { throw new XmlException("Negative numner of snags per resource unit."); } } else if (String.Equals(reader.Name, "branchRootC", StringComparison.Ordinal)) { this.BranchRootCarbon = reader.ReadElementContentAsFloat(); if (this.BranchRootCarbon < 0.0F) { throw new XmlException("Branch and root carbon is negative."); } } else if (String.Equals(reader.Name, "branchRootCN", StringComparison.Ordinal)) { this.BranchRootCarbonNitrogenRatio = reader.ReadElementContentAsFloat(); if (this.BranchRootCarbonNitrogenRatio < 0.0F) { throw new XmlException("Branch and root biomass carbon:nitrogen ratio is negative."); } } else if (String.Equals(reader.Name, "stemDecompRate", StringComparison.Ordinal)) { this.StemDecompositionRate = reader.ReadElementContentAsFloat(); if (this.StemDecompositionRate < 0.0F) { throw new XmlException("Standing woody debris decomposition rate is negative."); } } else if (String.Equals(reader.Name, "branchRootDecompRate", StringComparison.Ordinal)) { this.BranchRootDecompositionRate = reader.ReadElementContentAsFloat(); if (this.BranchRootDecompositionRate < 0.0F) { throw new XmlException("Wood decomposition rate is negative."); } } else if (String.Equals(reader.Name, "snagHalfLife", StringComparison.Ordinal)) { this.SnagHalfLife = reader.ReadElementContentAsFloat(); if (this.SnagHalfLife < 0.0F) { throw new XmlException("Half life of standing woody debris is negative."); } } else { throw new XmlException("Element '" + reader.Name + "' is unknown, has unexpected attributes, or is missing expected attributes."); } }
public override float ReadElementContentAsFloat() { return(_proxy.ReadElementContentAsFloat()); }
static void Main(string[] args) { ItemsData data = new ItemsData(); Item testitem = new Item(); Console.WriteLine("Welcome to Assignment 5 - Pokemon Edition"); PokemonReader reader = new PokemonReader(); Pokedex pokedex = reader.Load("pokemon151.xml"); // List out all the pokemons loaded foreach (Pokemon pokemon in pokedex.Pokemons) { Console.WriteLine(pokemon.Name); } // TODO: load the pokemon151 xml XmlDocument loadPokemon151 = new XmlDocument(); loadPokemon151.Load("pokemon151.xml"); // TODO: Add item reader and print out all the items using (XmlReader itemReader = XmlReader.Create("itemData.xml")) { while (itemReader.Read()) { if (itemReader.IsStartElement()) { switch (itemReader.Name.ToString()) { case "Name": Console.WriteLine("Item Name : " + itemReader.ReadElementContentAsString()); break; case "UnlockRequirement": Console.WriteLine("UnlockRequirement : " + itemReader.ReadElementContentAsFloat()); break; case "Description": Console.WriteLine("Description : " + itemReader.ReadElementContentAsString()); break; case "Effect": Console.WriteLine("Effect : " + itemReader.ReadElementContentAsString()); break; } data.Items.Add(testitem); } Console.WriteLine(""); } } // TODO: hook up item data to display with the inventory var source = new Inventory() { ItemToQuantity = new Dictionary <object, object> { { "Poke ball", 10 }, { "Potion", 10 } } }; // TODO: move this into a inventory with a serialize and deserialize function. source.Serialize(source); source.Deserialize("inventory.xml"); PokemonBag mybag = new PokemonBag(); mybag.Pokemons.Add(1); mybag.Pokemons.Add(1); mybag.Pokemons.Add(6); mybag.Pokemons.Add(151); mybag.Pokemons.Add(149); FileStream fs = new FileStream(@"serializePokemon.dat", FileMode.Create);//path of file BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, mybag); fs.Close(); fs = new FileStream(@"serializePokemon.dat", FileMode.Open); BinaryFormatter nbf = new BinaryFormatter(); PokemonBag mylist = nbf.Deserialize(fs) as PokemonBag; Console.WriteLine("\nList of the the pokemons caught"); foreach (int i in mylist.Pokemons) { Console.WriteLine(pokedex.GetPokemonByIndex(i).Name); } Console.WriteLine(pokedex.GetHighestHPPokemon().Name); Console.WriteLine(pokedex.GetHighestAttackPokemon().Name); Console.WriteLine(pokedex.GetHighestDefensePokemon().Name); Console.WriteLine(pokedex.GetHighestMaxCPPokemon().Name); // TODO: Add a pokemon bag with 2 bulbsaur, 1 charlizard, 1 mew and 1 dragonite // and save it out and load it back and list it out. Console.ReadKey(); }
public override float parseValue(XmlReader xmlReader) { return(xmlReader.ReadElementContentAsFloat()); }
protected override Object DoRead(XmlReader reader) { return(reader.ReadElementContentAsFloat()); }
public void SerializeFloat(string Key, ref float Value) { if (bReading) { Value = InternalReader.ReadElementContentAsFloat(Key, ""); } else { InternalWriter.WriteElementString(Key, Value.ToString()); } }
public void Deserialize(XmlReader reader) { m_name = reader.GetAttribute("name"); int version = Convert.ToInt32(reader.GetAttribute("version"), CultureInfo.InvariantCulture); reader.ReadStartElement(); //ParticleEffect m_particleID = reader.ReadElementContentAsInt(); m_length = reader.ReadElementContentAsFloat(); m_preload = reader.ReadElementContentAsFloat(); if (reader.Name == "LowRes") { LowRes = reader.ReadElementContentAsBoolean(); } bool isEmpty = reader.IsEmptyElement; reader.ReadStartElement(); //Generations while (reader.NodeType != XmlNodeType.EndElement) { MyParticleGeneration generation = MyParticlesManager.GenerationsPool.Allocate(); generation.Start(this); generation.Init(); generation.Deserialize(reader); AddGeneration(generation); } if (!isEmpty) { reader.ReadEndElement(); //Generations } if (reader.NodeType != XmlNodeType.EndElement) { isEmpty = reader.IsEmptyElement; reader.ReadStartElement(); //Particle lights while (reader.NodeType != XmlNodeType.EndElement) { MyParticleLight particleLight = MyParticlesManager.LightsPool.Allocate(); particleLight.Start(this); particleLight.Init(); particleLight.Deserialize(reader); AddParticleLight(particleLight); } if (!isEmpty) { reader.ReadEndElement(); //Particle lights } } reader.ReadEndElement(); //ParticleEffect }
/// <summary> /// Loads the status. /// </summary> /// <param name="reader">Reader.</param> protected override void LoadStatus (XmlReader reader) { base.LoadStatus (reader); reader.ReadToNextSibling ("Mana"); mana.value = reader.ReadElementContentAsFloat (); Debug.Log("Found Exp field: " + reader.ReadToNextSibling ("Exp")); Debug.Log("Found level field: " + reader.ReadToNextSibling ("Level")); GetComponent<Inventory> ().LoadInventory (reader); reader.ReadEndElement (); }
private ItemConsume LoadConsumeItem(XmlReader xmlReader, int id) { ItemConsume itemConsume = new ItemConsume(id, xmlReader.GetAttribute("name")); xmlReader.ReadToDescendant("description"); //<description> itemConsume.description = xmlReader.ReadElementContentAsString(); //<icon path=.../> if (xmlReader.ReadToNextSibling("icon") && xmlReader.GetAttribute(0) != "") { itemConsume.iconPath = xmlReader.GetAttribute(0); } else { itemConsume.iconPath = defaultSpritePath; } //<model path=.../> if (xmlReader.ReadToNextSibling("model") && xmlReader.GetAttribute(0) != "") { itemConsume.dropModelPath = xmlReader.GetAttribute(0); } else { itemConsume.dropModelPath = defaultDropModelPath; } if (xmlReader.ReadToNextSibling("salePrice")) //<salePrice>..</salePrice> { itemConsume.salePrice = xmlReader.ReadElementContentAsInt(); } else { itemConsume.salePrice = 0; } if (xmlReader.ReadToFollowing("numberTicks")) //<numberTicks> { itemConsume.numberTicks = xmlReader.ReadElementContentAsInt(); } else { itemConsume.numberTicks = 1; } if (xmlReader.ReadToFollowing("delayTick")) //<delayTick> { itemConsume.delayTick = xmlReader.ReadElementContentAsFloat(); } else { itemConsume.delayTick = 1.0f; } if (xmlReader.ReadToFollowing("maxInStack")) //<maxInStack> { itemConsume.maxInStack = xmlReader.ReadElementContentAsInt(); } else { itemConsume.maxInStack = 99; } //<atributes> if (xmlReader.ReadToNextSibling("atributes") && xmlReader.ReadToDescendant("add"))//<add.. { AtributeTypeItem tempType; float tempValue; do { tempType = (AtributeTypeItem)System.Enum.Parse(typeof(AtributeTypeItem), xmlReader.GetAttribute(0)); tempValue = xmlReader.ReadElementContentAsFloat(); itemConsume.itemAttributes.Add(new AttributeItem(tempType, tempValue)); } while (xmlReader.ReadToNextSibling("add")); } xmlReader.Close(); return(itemConsume); }
private ItemEquip LoadEquipItem(XmlReader xmlReader, int id) { ItemEquip itemEquip = new ItemEquip(id, xmlReader.GetAttribute("name")); itemEquip.itemEquipType = (ItemEquipType)System.Enum.Parse(typeof(ItemEquipType), xmlReader.GetAttribute("type")); xmlReader.ReadToDescendant("description"); //<description> itemEquip.description = xmlReader.ReadElementContentAsString(); //<icon path=.../> if (xmlReader.ReadToNextSibling("icon") && xmlReader.GetAttribute(0) != "") { itemEquip.iconPath = xmlReader.GetAttribute(0); } else { itemEquip.iconPath = defaultSpritePath; } //<model path=.../> if (xmlReader.ReadToNextSibling("model") && xmlReader.GetAttribute(0) != "") { itemEquip.dropModelPath = xmlReader.GetAttribute(0); } else { itemEquip.dropModelPath = defaultDropModelPath; } if (xmlReader.ReadToNextSibling("salePrice")) //<salePrice>..</salePrice> { itemEquip.salePrice = xmlReader.ReadElementContentAsInt(); } else { itemEquip.salePrice = 0; } if (xmlReader.ReadToNextSibling("requests")) { //<requests lvl=.. str=.. agi=.. vit=.. ene=.. /> int.TryParse(xmlReader.GetAttribute("lvl"), out itemEquip.requestLevel); int.TryParse(xmlReader.GetAttribute("str"), out itemEquip.requestStrenght); int.TryParse(xmlReader.GetAttribute("agi"), out itemEquip.requestAgility); int.TryParse(xmlReader.GetAttribute("vit"), out itemEquip.requestVitality); int.TryParse(xmlReader.GetAttribute("ene"), out itemEquip.requestEnergy); } else { itemEquip.requestLevel = 1; itemEquip.requestStrenght = 0; itemEquip.requestAgility = 0; itemEquip.requestVitality = 0; itemEquip.requestEnergy = 0; } //<atributes> if (xmlReader.ReadToNextSibling("atributes") && xmlReader.ReadToDescendant("add"))//<add.. { AtributeTypeItem tempType; float tempValue; do { tempType = (AtributeTypeItem)System.Enum.Parse(typeof(AtributeTypeItem), xmlReader.GetAttribute(0)); tempValue = xmlReader.ReadElementContentAsFloat(); itemEquip.itemAttributes.Add(new AttributeItem(tempType, tempValue)); } while (xmlReader.ReadToNextSibling("add")); } xmlReader.Close(); return(itemEquip); }
public static ExtensionInfo ReadExtensionInfo(string folderpath) { if (!ExtensionInfo.ExtensionExists(folderpath)) { throw new FileNotFoundException("No extension info exists for folder " + folderpath); } ExtensionInfo extensionInfo = new ExtensionInfo(); extensionInfo.FolderPath = folderpath; extensionInfo.Language = "en-us"; using (FileStream fileStream = File.OpenRead(folderpath + "/ExtensionInfo.xml")) { XmlReader xmlReader = XmlReader.Create((Stream)fileStream); while (!xmlReader.EOF) { if (xmlReader.Name == "Name") { int content = (int)xmlReader.MoveToContent(); extensionInfo.Name = Utils.CleanStringToLanguageRenderable(xmlReader.ReadElementContentAsString()); } if (xmlReader.Name == "Language") { int content = (int)xmlReader.MoveToContent(); extensionInfo.Language = xmlReader.ReadElementContentAsString(); } if (xmlReader.Name == "AllowSaves") { int content = (int)xmlReader.MoveToContent(); extensionInfo.AllowSave = xmlReader.ReadElementContentAsBoolean(); } if (xmlReader.Name == "StartingVisibleNodes") { int content = (int)xmlReader.MoveToContent(); string str = xmlReader.ReadElementContentAsString(); extensionInfo.StartingVisibleNodes = str.Split(new char[6] { ',', ' ', '\t', '\n', '\r', '/' }, StringSplitOptions.RemoveEmptyEntries); } if (xmlReader.Name == "StartingMission") { int content = (int)xmlReader.MoveToContent(); extensionInfo.StartingMissionPath = xmlReader.ReadElementContentAsString(); if (extensionInfo.StartingMissionPath == "NONE") { extensionInfo.StartingMissionPath = (string)null; } } if (xmlReader.Name == "StartingActions") { int content = (int)xmlReader.MoveToContent(); extensionInfo.StartingActionsPath = xmlReader.ReadElementContentAsString(); if (extensionInfo.StartingActionsPath == "NONE") { extensionInfo.StartingActionsPath = (string)null; } } if (xmlReader.Name == "Description") { int content = (int)xmlReader.MoveToContent(); extensionInfo.Description = Utils.CleanFilterStringToRenderable(xmlReader.ReadElementContentAsString()); } if (xmlReader.Name == "Faction") { int content = (int)xmlReader.MoveToContent(); extensionInfo.FactionDescriptorPaths.Add(xmlReader.ReadElementContentAsString()); } if (xmlReader.Name == "StartsWithTutorial") { int content = (int)xmlReader.MoveToContent(); extensionInfo.StartsWithTutorial = xmlReader.ReadElementContentAsString().ToLower() == "true"; } if (xmlReader.Name == "HasIntroStartup") { int content = (int)xmlReader.MoveToContent(); extensionInfo.HasIntroStartup = xmlReader.ReadElementContentAsString().ToLower() == "true"; } if (xmlReader.Name == "StartingTheme") { int content = (int)xmlReader.MoveToContent(); string lower = xmlReader.ReadElementContentAsString().ToLower(); extensionInfo.Theme = lower; } if (xmlReader.Name == "IntroStartupSong") { int content = (int)xmlReader.MoveToContent(); string str = xmlReader.ReadElementContentAsString(); extensionInfo.IntroStartupSong = str; } if (xmlReader.Name == "IntroStartupSongDelay") { int content = (int)xmlReader.MoveToContent(); float num = xmlReader.ReadElementContentAsFloat(); extensionInfo.IntroStartupSongDelay = num; } if (xmlReader.Name == "SequencerSpinUpTime") { int content = (int)xmlReader.MoveToContent(); float num = xmlReader.ReadElementContentAsFloat(); extensionInfo.SequencerSpinUpTime = num; } if (xmlReader.Name == "ActionsToRunOnSequencerStart") { int content = (int)xmlReader.MoveToContent(); string str = xmlReader.ReadElementContentAsString(); extensionInfo.ActionsToRunOnSequencerStart = str; } if (xmlReader.Name == "SequencerFlagRequiredForStart") { int content = (int)xmlReader.MoveToContent(); string str = xmlReader.ReadElementContentAsString(); extensionInfo.SequencerFlagRequiredForStart = str; } if (xmlReader.Name == "SequencerTargetID") { int content = (int)xmlReader.MoveToContent(); string str = xmlReader.ReadElementContentAsString(); extensionInfo.SequencerTargetID = str; } if (xmlReader.Name == "WorkshopDescription") { int content = (int)xmlReader.MoveToContent(); extensionInfo.WorkshopDescription = xmlReader.ReadElementContentAsString(); } if (xmlReader.Name == "WorkshopVisibility") { int content = (int)xmlReader.MoveToContent(); extensionInfo.WorkshopVisibility = (byte)xmlReader.ReadElementContentAsInt(); } if (xmlReader.Name == "WorkshopTags") { int content = (int)xmlReader.MoveToContent(); extensionInfo.WorkshopTags = xmlReader.ReadElementContentAsString(); } if (xmlReader.Name == "WorkshopPreviewImagePath") { int content = (int)xmlReader.MoveToContent(); extensionInfo.WorkshopPreviewImagePath = xmlReader.ReadElementContentAsString(); } if (xmlReader.Name == "WorkshopLanguage") { int content = (int)xmlReader.MoveToContent(); extensionInfo.WorkshopLanguage = xmlReader.ReadElementContentAsString(); } if (xmlReader.Name == "WorkshopPublishID") { int content = (int)xmlReader.MoveToContent(); extensionInfo.WorkshopPublishID = xmlReader.ReadElementContentAsString(); } xmlReader.Read(); } } string path = folderpath + "/Logo"; bool flag = false; if (File.Exists(path + ".png")) { path += ".png"; flag = true; } else if (File.Exists(path + ".jpg")) { path += ".png"; flag = true; } if (flag) { using (FileStream fileStream = File.OpenRead(path)) extensionInfo.LogoImage = Texture2D.FromStream(Game1.getSingleton().GraphicsDevice, (Stream)fileStream); } return(extensionInfo); }
public void ReadXml(XmlReader reader) { XmlSerializer sr = new XmlSerializer(typeof(int)); int depth = reader.Depth; if (!reader.IsEmptyElement && reader.Read()) { try { if (reader.Depth == depth + 1 && reader.NodeType != XmlNodeType.EndElement) { sr = new XmlSerializer(typeof(float)); reader.MoveToContent(); reader.Read(); this.posicaoReal.X = reader.ReadElementContentAsFloat(); this.posicaoReal.Y = reader.ReadElementContentAsFloat(); reader.MoveToContent(); reader.ReadToNextSibling("Velocidade"); reader.MoveToContent(); reader.Read(); this.velocidade.X = reader.ReadElementContentAsFloat(); this.velocidade.Y = reader.ReadElementContentAsFloat(); reader.MoveToContent(); reader.ReadToNextSibling("NomeTextura"); this.nomeTextura = reader.ReadElementContentAsString(); this.nomeTexturaCompleta = reader.ReadElementContentAsString(); this.nomeTexturaHUD = reader.ReadElementContentAsString(); this.tipo = reader.ReadElementContentAsString(); Boolean.TryParse((string)reader.ReadElementContentAsString(), out this.nuvem); Boolean.TryParse((string)reader.ReadElementContentAsString(), out this.coletavel); Boolean.TryParse((string)reader.ReadElementContentAsString(), out this.passavel); Boolean.TryParse((string)reader.ReadElementContentAsString(), out this.ativado); Boolean.TryParse((string)reader.ReadElementContentAsString(), out this.objetivo); sr = new XmlSerializer(typeof(AnimacaoDeSprites)); this.Animacao = (AnimacaoDeSprites)sr.Deserialize(reader); this.ItemInterativo = reader.ReadElementContentAsInt(); this.CordaInterativa = reader.ReadElementContentAsInt(); this.CordaDe = reader.ReadElementContentAsInt(); this.Peso = reader.ReadElementContentAsInt(); sr = new XmlSerializer(typeof(Color)); this.Cor = (Color)sr.Deserialize(reader); this.AnimacaoAtual = reader.ReadElementContentAsString(); } else { reader.Read(); } } catch (Exception ex) { throw ex; } } reader.Read(); }
private void parseXML(UnitStats stats, string xml) { XmlReader reader = XmlReader.Create(new StringReader(xml)); // maxHealth reader.ReadToFollowing("maxHealth"); stats.maxHealth = (short)reader.ReadElementContentAsInt(); // speed reader.ReadToFollowing("speed"); stats.speed = reader.ReadElementContentAsFloat(); // attackRange reader.ReadToFollowing("attackRange"); stats.attackRange = reader.ReadElementContentAsFloat(); // attack reader.ReadToFollowing("attack"); stats.attack = (short)reader.ReadElementContentAsInt(); // attackTicks reader.ReadToFollowing("attackTicks"); stats.attackTicks = (byte)reader.ReadElementContentAsInt(); //visibilityRange reader.ReadToFollowing("visibilityRange"); stats.visibilityRange = reader.ReadContentAsFloat(); //buildSpeed reader.ReadToFollowing("buildSpeed"); stats.buildSpeed = (byte)reader.ReadContentAsInt(); //waterCost reader.ReadToFollowing("waterCost"); stats.waterCost = (byte)reader.ReadContentAsInt(); //foodCost reader.ReadToFollowing("foodCost"); stats.foodCost = (byte)reader.ReadContentAsInt(); //lumberCost reader.ReadToFollowing("lumberCost"); stats.lumberCost = (byte)reader.ReadContentAsInt(); //metalCost reader.ReadToFollowing("metalCost"); stats.metalCost = (byte)reader.ReadContentAsInt(); //canAttack reader.ReadToFollowing("canAttack"); stats.canAttack = reader.ReadElementContentAsBoolean(); //canHarvest reader.ReadToFollowing("canHarvest"); stats.canHarvest = reader.ReadElementContentAsBoolean(); //canBuild reader.ReadToFollowing("canBuild"); stats.canBuild = reader.ReadElementContentAsBoolean(); //isZombie reader.ReadToFollowing("isZombie"); stats.isZombie = reader.ReadElementContentAsBoolean(); }
private static EasyTrackerConfig LoadConfigXml(XmlReader reader) { var result = new EasyTrackerConfig(); reader.ReadStartElement("analytics"); do { if (reader.IsStartElement()) { switch (reader.Name) { case "trackingId": result.TrackingId = reader.ReadElementContentAsString(); break; case "appName": result.AppName = reader.ReadElementContentAsString(); break; case "appVersion": result.AppVersion = reader.ReadElementContentAsString(); break; case "sampleFrequency": result.SampleFrequency = reader.ReadElementContentAsFloat(); break; case "dispatchPeriod": var dispatchPeriodInSeconds = reader.ReadElementContentAsInt(); result.DispatchPeriod = TimeSpan.FromSeconds(dispatchPeriodInSeconds); break; case "sessionTimeout": var sessionTimeoutInSeconds = reader.ReadElementContentAsInt(); result.SessionTimeout = (sessionTimeoutInSeconds >= 0) ? TimeSpan.FromSeconds(sessionTimeoutInSeconds) : (TimeSpan?)null; break; case "debug": result.Debug = reader.ReadElementContentAsBoolean(); break; case "autoAppLifetimeTracking": result.AutoAppLifetimeTracking = reader.ReadElementContentAsBoolean(); break; case "autoAppLifetimeMonitoring": result.AutoAppLifetimeMonitoring = reader.ReadElementContentAsBoolean(); break; case "anonymizeIp": result.AnonymizeIp = reader.ReadElementContentAsBoolean(); break; case "reportUncaughtExceptions": result.ReportUncaughtExceptions = reader.ReadElementContentAsBoolean(); break; case "useSecure": result.UseSecure = reader.ReadElementContentAsBoolean(); break; case "autoTrackNetworkConnectivity": result.AutoTrackNetworkConnectivity = reader.ReadElementContentAsBoolean(); break; default: reader.Skip(); break; } } else { reader.ReadEndElement(); break; } }while (true); return(result); }
public object ReadObject(Type type) { if (serialized_object_count++ == serializer.MaxItemsInObjectGraph) { throw SerializationError(String.Format("The object graph exceeded the maximum object count '{0}' specified in the serializer", serializer.MaxItemsInObjectGraph)); } bool nullable = false; if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>)) { nullable = true; type = Nullable.GetUnderlyingType(type); } bool isNull = reader.GetAttribute("type") == "null"; switch (Type.GetTypeCode(type)) { case TypeCode.DBNull: string dbn = reader.ReadElementContentAsString(); if (dbn != String.Empty) { throw new SerializationException(String.Format("The only expected DBNull value string is '{{}}'. Tha actual input was '{0}'.", dbn)); } return(DBNull.Value); case TypeCode.String: if (isNull) { reader.ReadElementContentAsString(); return(null); } else { return(reader.ReadElementContentAsString()); } case TypeCode.Char: var c = reader.ReadElementContentAsString(); if (c.Length > 1) { throw new XmlException("Invalid JSON char"); } return(Char.Parse(c)); case TypeCode.Single: return(reader.ReadElementContentAsFloat()); case TypeCode.Double: return(reader.ReadElementContentAsDouble()); case TypeCode.Decimal: return(reader.ReadElementContentAsDecimal()); case TypeCode.Byte: case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.UInt16: if (type.IsEnum) { return(Enum.ToObject(type, Convert.ChangeType(reader.ReadElementContentAsLong(), Enum.GetUnderlyingType(type), null))); } else { return(Convert.ChangeType(reader.ReadElementContentAsDecimal(), type, null)); } case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: if (type.IsEnum) { return(Enum.ToObject(type, Convert.ChangeType(reader.ReadElementContentAsLong(), Enum.GetUnderlyingType(type), null))); } else { return(Convert.ChangeType(reader.ReadElementContentAsDecimal(), type, null)); } case TypeCode.Boolean: return(reader.ReadElementContentAsBoolean()); case TypeCode.DateTime: // it does not use ReadElementContentAsDateTime(). Different string format. var s = reader.ReadElementContentAsString(); if (s.Length < 2 || !s.StartsWith("/Date(", StringComparison.Ordinal) || !s.EndsWith(")/", StringComparison.Ordinal)) { if (nullable) { return(null); } throw new XmlException("Invalid JSON DateTime format. The value format should be '/Date(UnixTime)/'"); } // The date can contain [SIGN]LONG, [SIGN]LONG+HOURSMINUTES or [SIGN]LONG-HOURSMINUTES // the format for HOURSMINUTES is DDDD int tidx = s.IndexOf('-', 8); if (tidx == -1) { tidx = s.IndexOf('+', 8); } int minutes = 0; if (tidx == -1) { s = s.Substring(6, s.Length - 8); } else { int offset; int.TryParse(s.Substring(tidx + 1, s.Length - 3 - tidx), out offset); minutes = (offset % 100) + (offset / 100) * 60; if (s [tidx] == '-') { minutes = -minutes; } s = s.Substring(6, tidx - 6); } var date = new DateTime(1970, 1, 1).AddMilliseconds(long.Parse(s)); if (minutes != 0) { date = date.AddMinutes(minutes); } return(date); default: if (type == typeof(Guid)) { return(new Guid(reader.ReadElementContentAsString())); } else if (type == typeof(Uri)) { if (isNull) { reader.ReadElementContentAsString(); return(null); } else { return(new Uri(reader.ReadElementContentAsString(), UriKind.RelativeOrAbsolute)); } } else if (type == typeof(XmlQualifiedName)) { s = reader.ReadElementContentAsString(); int idx = s.IndexOf(':'); return(idx < 0 ? new XmlQualifiedName(s) : new XmlQualifiedName(s.Substring(0, idx), s.Substring(idx + 1))); } else if (type != typeof(object)) { // strongly-typed object if (reader.IsEmptyElement) { // empty -> null array or object reader.Read(); return(null); } Type ct = GetCollectionElementType(type); if (ct != null) { return(DeserializeGenericCollection(type, ct)); } else { TypeMap map = GetTypeMap(type); return(map.Deserialize(this)); } } else { return(ReadInstanceDrivenObject()); } } }
public override float ReadElementContentAsFloat() { return(innerReader.ReadElementContentAsFloat()); }
/// <summary> /// Loads the XML data to the current session. /// </summary> /// <returns>Returns false if the save file indicates an automatic save (after gameover) or cannot be read</returns> public bool Load() { if (System.IO.File.Exists(_exeDirectory + FileName) == true) { _reader = XmlReader.Create(_exeDirectory + FileName); try { int count; int ID; int parentID; int ageInMillliSecs; int hitPoints; Banjo.BanjoType type; float x; float y; while (_reader.Read() == true) { if (_reader.IsStartElement()) { switch (_reader.Name) { case "savegame": _reader.ReadToFollowing("highScore"); _playfield.HighScore.Value = _reader.ReadElementContentAsInt(); _reader.ReadToFollowing("userSave"); if (_reader.ReadElementContentAsBoolean() == false) { _reader.Close(); return(false); } _reader.ReadToFollowing("IDCount"); _playfield.IDCount = _reader.ReadElementContentAsInt(); break; case "player": _reader.ReadToFollowing("ID"); _playfield.Player.ID = _reader.ReadElementContentAsInt(); _reader.ReadToFollowing("score"); _playfield.Player.Score.Value = _reader.ReadElementContentAsInt(); _reader.ReadToFollowing("lives"); _playfield.Player.Lives = _reader.ReadElementContentAsInt(); _reader.ReadToFollowing("location"); _reader.ReadToFollowing("x"); _playfield.Player.Location.X = _reader.ReadElementContentAsFloat(); _reader.ReadToFollowing("y"); _playfield.Player.Location.Y = _reader.ReadElementContentAsFloat(); break; case "notes": _reader.ReadToFollowing("count"); count = _reader.ReadElementContentAsInt(); while (count > 0) { _reader.ReadToFollowing("ID"); ID = _reader.ReadElementContentAsInt(); _reader.ReadToFollowing("parentID"); parentID = _reader.ReadElementContentAsInt(); _reader.ReadToFollowing("x"); x = _reader.ReadElementContentAsFloat(); _reader.ReadToFollowing("y"); y = _reader.ReadElementContentAsFloat(); _playfield.LoadNote(ID, parentID, x, y); count--; } break; case "banjos": _reader.ReadToFollowing("count"); count = _reader.ReadElementContentAsInt(); while (count > 0) { _reader.ReadToFollowing("ID"); ID = _reader.ReadElementContentAsInt(); _reader.ReadToFollowing("age"); ageInMillliSecs = _reader.ReadElementContentAsInt(); _reader.ReadToFollowing("hitPoints"); hitPoints = _reader.ReadElementContentAsInt(); _reader.ReadToFollowing("type"); type = (Banjo.BanjoType)Enum.Parse(typeof(Banjo.BanjoType), _reader.ReadElementContentAsString()); _reader.ReadToFollowing("x"); x = _reader.ReadElementContentAsFloat(); _reader.ReadToFollowing("y"); y = _reader.ReadElementContentAsFloat(); _playfield.LoadBanjo(ID, type, x, y, ageInMillliSecs); count--; } break; } } } _reader.Close(); } catch (Exception e) { try { File.Delete(_exeDirectory + FileName); } catch { Debug.WriteLine("Failed to delete settings file " + FileName + "." + e.Message); } return(false); } } else { return(false); } return(true); }
public void Deserialize(XmlReader reader) { m_name = reader.GetAttribute("name"); int version = Convert.ToInt32(reader.GetAttribute("version"), CultureInfo.InvariantCulture); reader.ReadStartElement(); //ParticleEffect m_particleID = reader.ReadElementContentAsInt(); m_length = reader.ReadElementContentAsFloat(); if (reader.Name == "LowRes") { LowRes = reader.ReadElementContentAsBoolean(); } if (reader.Name == "Scale") { m_globalScale = reader.ReadElementContentAsFloat(); } bool isEmpty = reader.IsEmptyElement; reader.ReadStartElement(); //Generations while (reader.NodeType != XmlNodeType.EndElement) { if (isEmpty) { break; } if (reader.Name == "ParticleGeneration") { MyParticleGeneration generation; MyParticlesManager.GenerationsPool.AllocateOrCreate(out generation); generation.Start(this); generation.Init(); generation.Deserialize(reader); AddGeneration(generation); } else if (reader.Name == "ParticleGPUGeneration") { MyParticleGPUGeneration generation; MyParticlesManager.GPUGenerationsPool.AllocateOrCreate(out generation); generation.Start(this); generation.Init(); generation.Deserialize(reader); AddGeneration(generation); } else { reader.Read(); } } if (!isEmpty) { reader.ReadEndElement(); //Generations } if (reader.NodeType != XmlNodeType.EndElement) { isEmpty = reader.IsEmptyElement; if (isEmpty) { reader.Read(); } else { reader.ReadStartElement(); //Particle lights while (reader.NodeType != XmlNodeType.EndElement) { MyParticleLight particleLight; MyParticlesManager.LightsPool.AllocateOrCreate(out particleLight); particleLight.Start(this); particleLight.Init(); particleLight.Deserialize(reader); AddParticleLight(particleLight); } reader.ReadEndElement(); //Particle lights } } if (reader.NodeType != XmlNodeType.EndElement) { isEmpty = reader.IsEmptyElement; if (isEmpty) { reader.Read(); } else { reader.ReadStartElement(); //Particle sounds while (reader.NodeType != XmlNodeType.EndElement) { MyParticleSound particleSound; MyParticlesManager.SoundsPool.AllocateOrCreate(out particleSound); particleSound.Start(this); particleSound.Init(); particleSound.Deserialize(reader); AddParticleSound(particleSound); } reader.ReadEndElement(); //Particle sounds } } reader.ReadEndElement(); //ParticleEffect }
protected override void ReadStartElement(XmlReader reader) { if (reader.AttributeCount != 0) { throw new XmlException("Encountered unexpected attributes on element " + reader.Name + "."); } if (String.Equals(reader.Name, "nitrogenResponseClasses", StringComparison.Ordinal)) { reader.Read(); } else if (String.Equals(reader.Name, "class1k", StringComparison.Ordinal)) { this.Class1K = reader.ReadElementContentAsFloat(); if (this.Class1K >= 0.0F) { throw new XmlException("Class 1 nitrogen response: a is zero or positive."); } } else if (String.Equals(reader.Name, "class1minimum", StringComparison.Ordinal)) { this.Class1Minimum = reader.ReadElementContentAsFloat(); if (this.Class1Minimum <= 0.0F) { throw new XmlException("Class 1 nitrogen response: b is zero or negative."); } } else if (String.Equals(reader.Name, "class2k", StringComparison.Ordinal)) { this.Class2K = reader.ReadElementContentAsFloat(); if (this.Class2K >= 0.0F) { throw new XmlException("Class 2 nitrogen response: a is zero or positive."); } } else if (String.Equals(reader.Name, "class2minimum", StringComparison.Ordinal)) { this.Class2Minimum = reader.ReadElementContentAsFloat(); if (this.Class2Minimum <= 0.0F) { throw new XmlException("Class 2 nitrogen response: b is zero or negative."); } } else if (String.Equals(reader.Name, "class3k", StringComparison.Ordinal)) { this.Class3K = reader.ReadElementContentAsFloat(); if (this.Class3K >= 0.0F) { throw new XmlException("Class 3 nitrogen response: a is zero or positive."); } } else if (String.Equals(reader.Name, "class3minimum", StringComparison.Ordinal)) { this.Class3Minimum = reader.ReadElementContentAsFloat(); if (this.Class3Minimum <= 0.0F) { throw new XmlException("Class 3 nitrogen response: b is zero or negative."); } } else { throw new XmlException("Element '" + reader.Name + "' is unknown, has unexpected attributes, or is missing expected attributes."); } }
//[Variation("1. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 1)] //[Variation("2. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 2)] //[Variation("3. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 3)] //[Variation("4. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 4)] //[Variation("5. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 5)] //[Variation("6. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 6)] //[Variation("7. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 7)] //[Variation("8. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 8)] //[Variation("9. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 9)] //[Variation("10. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 10)] //[Variation("11. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 11)] //[Variation("12. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 12)] //[Variation("13. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 13)] //[Variation("14. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 14)] //[Variation("15. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 15)] //[Variation("16. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 16)] //[Variation("17. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 17)] //[Variation("18. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 18)] //[Variation("19. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 19)] //[Variation("20. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 20)] //[Variation("21. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 21)] //[Variation("22. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 22)] //[Variation("23. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 23)] //[Variation("24. Close on a subtree reader that is in error state gets doesn't it into in infinite loop", Param = 24)] public int DisposingSubtreeReaderThatIsInErrorStateWorksProperly() { int param = (int)CurVariation.Param; byte[] b = new byte[4]; string xml = "<Report><Account><Balance>-4,095,783.00" + "</Balance><LastActivity>2006/01/05</LastActivity>" + "</Account></Report>"; ReloadSourceStr(xml); while (DataReader.Name != "Account") { DataReader.Read(); } XmlReader sub = DataReader.ReadSubtree(); while (sub.Read()) { if (sub.Name == "Balance") { try { switch (param) { case 1: decimal num1 = sub.ReadElementContentAsDecimal(); break; case 2: object num2 = sub.ReadElementContentAs(typeof(float), null); break; case 3: bool num3 = sub.ReadElementContentAsBoolean(); break; case 5: float num5 = sub.ReadElementContentAsFloat(); break; case 6: double num6 = sub.ReadElementContentAsDouble(); break; case 7: int num7 = sub.ReadElementContentAsInt(); break; case 8: long num8 = sub.ReadElementContentAsLong(); break; case 9: object num9 = sub.ReadElementContentAs(typeof(double), null); break; case 10: object num10 = sub.ReadElementContentAs(typeof(decimal), null); break; case 11: sub.Read(); decimal num11 = sub.ReadContentAsDecimal(); break; case 12: sub.Read(); object num12 = sub.ReadContentAs(typeof(float), null); break; case 13: sub.Read(); bool num13 = sub.ReadContentAsBoolean(); break; case 15: sub.Read(); float num15 = sub.ReadContentAsFloat(); break; case 16: sub.Read(); double num16 = sub.ReadContentAsDouble(); break; case 17: sub.Read(); int num17 = sub.ReadContentAsInt(); break; case 18: sub.Read(); long num18 = sub.ReadContentAsLong(); break; case 19: sub.Read(); object num19 = sub.ReadContentAs(typeof(double), null); break; case 20: sub.Read(); object num20 = sub.ReadContentAs(typeof(decimal), null); break; case 21: object num21 = sub.ReadElementContentAsBase64(b, 0, 2); break; case 22: object num22 = sub.ReadElementContentAsBinHex(b, 0, 2); break; case 23: sub.Read(); object num23 = sub.ReadContentAsBase64(b, 0, 2); break; case 24: sub.Read(); object num24 = sub.ReadContentAsBinHex(b, 0, 2); break; } } catch (XmlException) { try { switch (param) { case 1: decimal num1 = sub.ReadElementContentAsDecimal(); break; case 2: object num2 = sub.ReadElementContentAs(typeof(float), null); break; case 3: bool num3 = sub.ReadElementContentAsBoolean(); break; case 5: float num5 = sub.ReadElementContentAsFloat(); break; case 6: double num6 = sub.ReadElementContentAsDouble(); break; case 7: int num7 = sub.ReadElementContentAsInt(); break; case 8: long num8 = sub.ReadElementContentAsLong(); break; case 9: object num9 = sub.ReadElementContentAs(typeof(double), null); break; case 10: object num10 = sub.ReadElementContentAs(typeof(decimal), null); break; case 11: sub.Read(); decimal num11 = sub.ReadContentAsDecimal(); break; case 12: sub.Read(); object num12 = sub.ReadContentAs(typeof(float), null); break; case 13: sub.Read(); bool num13 = sub.ReadContentAsBoolean(); break; case 15: sub.Read(); float num15 = sub.ReadContentAsFloat(); break; case 16: sub.Read(); double num16 = sub.ReadContentAsDouble(); break; case 17: sub.Read(); int num17 = sub.ReadContentAsInt(); break; case 18: sub.Read(); long num18 = sub.ReadContentAsLong(); break; case 19: sub.Read(); object num19 = sub.ReadContentAs(typeof(double), null); break; case 20: sub.Read(); object num20 = sub.ReadContentAs(typeof(decimal), null); break; case 21: object num21 = sub.ReadElementContentAsBase64(b, 0, 2); break; case 22: object num22 = sub.ReadElementContentAsBinHex(b, 0, 2); break; case 23: sub.Read(); object num23 = sub.ReadContentAsBase64(b, 0, 2); break; case 24: sub.Read(); object num24 = sub.ReadContentAsBinHex(b, 0, 2); break; } } catch (InvalidOperationException) { return(TEST_PASS); } catch (XmlException) { return(TEST_PASS); } if (param == 24 || param == 23) { return(TEST_PASS); } } catch (NotSupportedException) { return(TEST_PASS); } } } return(TEST_FAIL); }
protected override void ReadStartElement(XmlReader reader) { if (reader.AttributeCount != 0) { throw new XmlException("Encountered unexpected attributes on element " + reader.Name + "."); } if (String.Equals(reader.Name, "geometry", StringComparison.Ordinal)) { reader.Read(); } else if (String.Equals(reader.Name, "lightCellSize", StringComparison.Ordinal)) { this.LightCellSize = reader.ReadElementContentAsFloat(); if (this.LightCellSize <= 0.0F) { throw new XmlException("Light cell size is zero or negative."); } } else if (String.Equals(reader.Name, "torus", StringComparison.Ordinal)) { this.IsTorus = reader.ReadElementContentAsBoolean(); } else if (String.Equals(reader.Name, "width", StringComparison.Ordinal)) { this.Width = reader.ReadElementContentAsFloat(); if (this.Width <= 0.0F) { throw new XmlException("Model width is zero or negative."); } } else if (String.Equals(reader.Name, "height", StringComparison.Ordinal)) { this.Height = reader.ReadElementContentAsFloat(); if (this.Height <= 0.0F) { throw new XmlException("Model height is zero or negative."); } } else if (String.Equals(reader.Name, "buffer", StringComparison.Ordinal)) { this.Buffer = reader.ReadElementContentAsFloat(); if (this.Buffer <= 0.0F) { throw new XmlException("Light buffer width is zero or negative."); } } else if (String.Equals(reader.Name, "latitude", StringComparison.Ordinal)) { this.Latitude = reader.ReadElementContentAsFloat(); if ((this.Latitude < -90.0F) || (this.Latitude > 90.0F)) { throw new XmlException("Latitude is not between -90 and 90°."); } } else if (String.Equals(reader.Name, "modelOrigin", StringComparison.Ordinal)) { Debug.Assert(this.ModelOrigin == null); this.ModelOrigin = new ModelOrigin(); this.ModelOrigin.ReadXml(reader); } else { throw new XmlException("Element '" + reader.Name + "' is unknown, has unexpected attributes, or is missing expected attributes."); } }
/// <summary> /// Gets a file of game settings from the file name /// </summary> /// <param name="extension">Where the file is located</param> /// <returns>The game settings from resources</returns> public static GameSettings LoadGameSettingsXML(string extension) { // Get a default settings in case none exists GameSettings data = new GameSettings(); TextAsset xmlFile = (TextAsset)Resources.Load(xmlSettingsDataPath + extension); Debug.Log(xmlFile); if (xmlFile != null) { MemoryStream assetStream = new MemoryStream(xmlFile.bytes); XmlReader reader = XmlReader.Create(assetStream); bool endofSettings = false; while (reader.Read() && !endofSettings) { if (reader.IsStartElement()) { switch (reader.LocalName) { case "Type": data.Type = (Enums.GameType)System.Enum.Parse(typeof(Enums.GameType), reader.ReadElementContentAsString()); break; case "TimeLimitEnabled": data.TimeLimitEnabled = reader.ReadElementContentAsBoolean(); break; case "TimeLimit": data.TimeLimit = reader.ReadElementContentAsFloat(); break; case "KillLimit": data.KillLimit = reader.ReadElementContentAsFloat(); break; case "StockLimit": data.StockLimit = reader.ReadElementContentAsFloat(); break; case "ArrowLimit": data.ArrowLimit = reader.ReadElementContentAsFloat(); break; case "DamageModifier": data.DamageModifier = reader.ReadElementContentAsFloat(); break; case "GravityModifier": data.GravityModifier = reader.ReadElementContentAsFloat(); break; case "SpeedModifier": data.SpeedModifier = reader.ReadElementContentAsFloat(); break; case "TokenSpawnFreq": data.TokenSpawnFreq = reader.ReadElementContentAsFloat(); break; case "PlayerSpawnFreq": data.PlayerSpawnFreq = reader.ReadElementContentAsFloat(); break; case "EnabledTokens": Dictionary <Enums.Tokens, Enums.Frequency> dict = new Dictionary <Enums.Tokens, Enums.Frequency>(); XmlReader inner = reader.ReadSubtree(); while (inner.Read()) { if (inner.IsStartElement()) { if (inner.LocalName.Equals("Token")) { Enums.Tokens t = (Enums.Tokens)System.Enum.Parse(typeof(Enums.Tokens), inner.ReadElementContentAsString()); inner.ReadToFollowing("Frequency"); Enums.Frequency f = (Enums.Frequency)System.Enum.Parse(typeof(Enums.Frequency), inner.ReadElementContentAsString()); dict.Add(t, f); } } } data.EnabledTokens = dict; inner.Close(); break; case "DefaultTokens": List <Enums.Tokens> defaultTokens = new List <Enums.Tokens>(); XmlReader tokens = reader.ReadSubtree(); while (tokens.Read()) { if (tokens.IsStartElement()) { if (tokens.LocalName.Equals("Token")) { Enums.Tokens t = (Enums.Tokens)System.Enum.Parse(typeof(Enums.Tokens), tokens.ReadElementContentAsString()); defaultTokens.Add(t); } } } data.DefaultTokens = defaultTokens; tokens.Close(); break; case "GameSettings": break; default: endofSettings = true; break; } } } reader.Close(); } return(data); }
public static List <BaseItemType> LoadItems() { List <BaseItemType> weapons = new List <BaseItemType>(); string folderPath = Directory.GetCurrentDirectory() + GlobalConstants.DATA_FOLDER + "Items"; string[] files = Directory.GetFiles(folderPath, "*.xml", SearchOption.AllDirectories); for (int i = 0; i < files.Length; i++) { XmlReader reader = XmlReader.Create(files[i]); List <IdentifiedItem> identifiedItems = new List <IdentifiedItem>(); List <UnidentifiedItem> unidentifiedItems = new List <UnidentifiedItem>(); string actionWord = "strikes"; string category = "Misc"; int lightLevel = 0; while (reader.Read()) { if (reader.Depth == 0 && reader.NodeType == XmlNodeType.Element && !reader.Name.Equals("Items")) { break; } if (reader.Name.Equals("Category") && reader.NodeType == XmlNodeType.Element) { category = reader.ReadElementContentAsString(); } if (reader.Name.Equals("IdentifiedItem") && reader.NodeType == XmlNodeType.Element) { IdentifiedItem item = new IdentifiedItem(); item.slot = "None"; item.skill = "None"; while (reader.NodeType != XmlNodeType.EndElement) { reader.Read(); if (reader.Name.Equals("Name")) { item.name = reader.ReadElementContentAsString(); } else if (reader.Name.Equals("Description")) { item.description = reader.ReadElementContentAsString(); } else if (reader.Name.Equals("Value")) { item.value = reader.ReadElementContentAsInt(); } else if (reader.Name.Equals("Effect")) { item.interactionFile = reader.ReadElementContentAsString(); } else if (reader.Name.Equals("SpawnWeight")) { item.weighting = reader.ReadElementContentAsInt(); } else if (reader.Name.Equals("Materials")) { string materials = reader.ReadElementContentAsString(); item.materials = materials.Split(','); } else if (reader.Name.Equals("Size")) { item.size = reader.ReadElementContentAsFloat(); } else if (reader.Name.Equals("Slot")) { item.slot = reader.ReadElementContentAsString(); } else if (reader.Name.Equals("Skill")) { item.skill = reader.ReadElementContentAsString(); } else if (reader.Name.Equals("LightLevel")) { lightLevel = reader.ReadElementContentAsInt(); } } item.category = category; identifiedItems.Add(item); } else if (reader.Name.Equals("UnidentifiedItem")) { UnidentifiedItem item = new UnidentifiedItem(); while (reader.NodeType != XmlNodeType.EndElement) { reader.Read(); if (reader.Name.Equals("Name")) { item.name = reader.ReadElementContentAsString(); } else if (reader.Name.Equals("Description")) { item.description = reader.ReadElementContentAsString(); } } unidentifiedItems.Add(item); } else if (reader.Name.Equals("ActionWord")) { actionWord = reader.ReadElementContentAsString(); } } reader.Close(); for (int j = 0; j < identifiedItems.Count; j++) { UnidentifiedItem chosenDescription = new UnidentifiedItem(identifiedItems[j].name, identifiedItems[j].description); if (unidentifiedItems.Count != 0) { int index = RNG.Roll(0, unidentifiedItems.Count - 1); chosenDescription = unidentifiedItems[index]; unidentifiedItems.RemoveAt(index); } for (int k = 0; k < identifiedItems[j].materials.Length; k++) { weapons.Add(new BaseItemType(identifiedItems[j].category, identifiedItems[j].description, chosenDescription.description, chosenDescription.name, identifiedItems[j].name, identifiedItems[j].slot, identifiedItems[j].size, MaterialHandler.GetMaterial(identifiedItems[j].materials[k]), identifiedItems[j].category, identifiedItems[j].skill, actionWord, identifiedItems[j].interactionFile, identifiedItems[j].value, identifiedItems[j].weighting, lightLevel)); } } } return(weapons); }
/// ----------------------------------------------------------------------------- /// <summary> /// Reads a RoleInfo from an XmlReader. /// </summary> /// <param name="reader">The XmlReader to use.</param> /// ----------------------------------------------------------------------------- public void ReadXml(XmlReader reader) { // Set status to approved by default this.Status = RoleStatus.Approved; while (reader.Read()) { if (reader.NodeType == XmlNodeType.EndElement) { break; } if (reader.NodeType == XmlNodeType.Whitespace) { continue; } if (reader.NodeType == XmlNodeType.Element) { switch (reader.Name.ToLowerInvariant()) { case "role": break; case "rolename": this.RoleName = reader.ReadElementContentAsString(); break; case "description": this.Description = reader.ReadElementContentAsString(); break; case "billingfrequency": this.BillingFrequency = reader.ReadElementContentAsString(); if (string.IsNullOrEmpty(this.BillingFrequency)) { this.BillingFrequency = "N"; } break; case "billingperiod": this.BillingPeriod = reader.ReadElementContentAsInt(); break; case "servicefee": this.ServiceFee = reader.ReadElementContentAsFloat(); if (this.ServiceFee < 0) { this.ServiceFee = 0; } break; case "trialfrequency": this.TrialFrequency = reader.ReadElementContentAsString(); if (string.IsNullOrEmpty(this.TrialFrequency)) { this.TrialFrequency = "N"; } break; case "trialperiod": this.TrialPeriod = reader.ReadElementContentAsInt(); break; case "trialfee": this.TrialFee = reader.ReadElementContentAsFloat(); if (this.TrialFee < 0) { this.TrialFee = 0; } break; case "ispublic": this.IsPublic = reader.ReadElementContentAsBoolean(); break; case "autoassignment": this.AutoAssignment = reader.ReadElementContentAsBoolean(); break; case "rsvpcode": this.RSVPCode = reader.ReadElementContentAsString(); break; case "iconfile": this.IconFile = reader.ReadElementContentAsString(); break; case "issystemrole": this.IsSystemRole = reader.ReadElementContentAsBoolean(); break; case "roletype": switch (reader.ReadElementContentAsString()) { case "adminrole": this._RoleType = RoleType.Administrator; break; case "registeredrole": this._RoleType = RoleType.RegisteredUser; break; case "subscriberrole": this._RoleType = RoleType.Subscriber; break; case "unverifiedrole": this._RoleType = RoleType.UnverifiedUser; break; default: this._RoleType = RoleType.None; break; } this._RoleTypeSet = true; break; case "securitymode": switch (reader.ReadElementContentAsString()) { case "securityrole": this.SecurityMode = SecurityMode.SecurityRole; break; case "socialgroup": this.SecurityMode = SecurityMode.SocialGroup; break; case "both": this.SecurityMode = SecurityMode.Both; break; } break; case "status": switch (reader.ReadElementContentAsString()) { case "pending": this.Status = RoleStatus.Pending; break; case "disabled": this.Status = RoleStatus.Disabled; break; default: this.Status = RoleStatus.Approved; break; } break; default: if (reader.NodeType == XmlNodeType.Element && !string.IsNullOrEmpty(reader.Name)) { reader.ReadElementContentAsString(); } break; } } } }
public static List <BaseItemType> LoadFood() { List <BaseItemType> food = new List <BaseItemType>(); string filePath = Directory.GetCurrentDirectory() + "//Data//Items//Food//Food.xml"; XmlReader reader = XmlReader.Create(filePath); List <IdentifiedItem> identifiedItems = new List <IdentifiedItem>(); string actionWord = "strikes"; string governingSkill = "None"; string category = "None"; while (reader.Read()) { if (reader.Depth == 0 && reader.NodeType == XmlNodeType.Element && !reader.Name.Equals("Items")) { break; } if (reader.Name.Equals("Category") && reader.NodeType == XmlNodeType.Element) { category = reader.ReadElementContentAsString(); } if (reader.Name.Equals("IdentifiedItem") && reader.NodeType == XmlNodeType.Element) { IdentifiedItem item = new IdentifiedItem(); while (reader.NodeType != XmlNodeType.EndElement) { reader.Read(); if (reader.Name.Equals("Name")) { item.name = reader.ReadElementContentAsString(); } else if (reader.Name.Equals("Description")) { item.description = reader.ReadElementContentAsString(); } else if (reader.Name.Equals("Value")) { item.value = reader.ReadElementContentAsInt(); } else if (reader.Name.Equals("Effect")) { item.interactionFile = Directory.GetCurrentDirectory() + "//Data//Scripts//Items//Food//" + reader.ReadElementContentAsString(); } else if (reader.Name.Equals("SpawnWeight")) { item.weighting = reader.ReadElementContentAsInt(); } else if (reader.Name.Equals("Materials")) { string materials = reader.ReadElementContentAsString(); item.materials = materials.Split(','); } else if (reader.Name.Equals("Size")) { item.size = reader.ReadElementContentAsFloat(); } } item.category = category; identifiedItems.Add(item); } else if (reader.Name.Equals("ActionWord")) { actionWord = reader.ReadElementContentAsString(); } } reader.Close(); ItemMaterial foodMaterial = MaterialHandler.GetMaterial("Food"); for (int i = 0; i < identifiedItems.Count; i++) { food.Add(new BaseItemType(identifiedItems[i].category, identifiedItems[i].description, identifiedItems[i].description, identifiedItems[i].name, identifiedItems[i].name, "None", identifiedItems[i].size, foodMaterial, "Food", governingSkill, actionWord, identifiedItems[i].interactionFile, identifiedItems[i].value, identifiedItems[i].weighting)); } return(food); }
static void Build() { string XmlFilePath = "Assets/Resources/revit.xml"; string text = File.ReadAllText(XmlFilePath); text = text.Replace("><", "> <"); File.WriteAllText(XmlFilePath, text); GameObject cube = Resources.Load("Cube") as GameObject; GameObject cylinder = Resources.Load("Cylinder") as GameObject; GameObject plane = Resources.Load("Plane") as GameObject; XmlReader reader = XmlReader.Create(XmlFilePath); GameObject building = new GameObject("Building"); float groundXMin = 0.0f, groundXMax = 0.0f, groundYMin = 0.0f, groundYMax = 0.0f, groundZMin = 0.0f, groundZMax = 0.0f; reader.ReadToFollowing("worldBounds"); while (true) { reader.Read(); if (reader.IsStartElement()) { switch (reader.Name) { case "xmin": groundXMin = reader.ReadElementContentAsFloat(); break; case "xmax": groundXMax = reader.ReadElementContentAsFloat(); break; case "ymin": groundYMin = reader.ReadElementContentAsFloat(); break; case "ymax": groundYMax = reader.ReadElementContentAsFloat(); break; case "zmin": groundZMin = reader.ReadElementContentAsFloat(); break; case "zmax": groundZMax = reader.ReadElementContentAsFloat(); break; } } if (reader.NodeType == XmlNodeType.EndElement) { break; } } GameObject ground = PrefabUtility.InstantiatePrefab(plane) as GameObject; ground.name = "Ground"; ground.transform.position = new Vector3(groundXMax + groundXMin, groundYMax + groundYMin, groundZMax + groundZMin) / 2.0f; ground.transform.localScale = new Vector3(groundXMax - groundXMin, groundYMax - groundYMin, groundZMax - groundZMin) / 20.0f; ground.transform.parent = building.transform; GameObjectUtility.SetStaticEditorFlags(ground, StaticEditorFlags.NavigationStatic); while (reader.Read()) { switch (reader.Name) { case "orientedBoxObstacle": { float thetaX = 0.0f, thetaY = 0.0f, thetaZ = 0.0f; float scaleX = 1.0f, scaleY = 1.0f, scaleZ = 1.0f; float posX_orientBox = 0.0f, posY_orientBox = 0.0f, posZ_orientBox = 0.0f; while (reader.Read() && reader.Name != "orientedBoxObstacle") { switch (reader.Name) { case "thetaX": thetaX = reader.ReadElementContentAsFloat(); break; case "thetaY": thetaY = reader.ReadElementContentAsFloat(); break; case "thetaZ": thetaZ = reader.ReadElementContentAsFloat(); break; case "size": while (reader.Read() && reader.Name != "size") { switch (reader.Name) { case "x": scaleX = reader.ReadElementContentAsFloat(); break; case "y": scaleY = reader.ReadElementContentAsFloat(); break; case "z": scaleZ = reader.ReadElementContentAsFloat(); break; } } break; case "position": while (reader.Read() && reader.Name != "position") { switch (reader.Name) { case "x": posX_orientBox = reader.ReadElementContentAsFloat(); break; case "y": posY_orientBox = reader.ReadElementContentAsFloat(); break; case "z": posZ_orientBox = reader.ReadElementContentAsFloat(); break; } } break; } } GameObject orientedBoxObstacle = PrefabUtility.InstantiatePrefab(cube) as GameObject; orientedBoxObstacle.name = "Oriented Box Obstacle"; orientedBoxObstacle.transform.position = new Vector3(posX_orientBox, posY_orientBox + scaleY / 2.0f, posZ_orientBox); orientedBoxObstacle.transform.rotation = Quaternion.Euler(thetaX, thetaY, thetaZ); orientedBoxObstacle.transform.localScale = new Vector3(scaleX, scaleY, scaleZ); orientedBoxObstacle.transform.parent = building.transform; GameObjectUtility.SetStaticEditorFlags(orientedBoxObstacle, StaticEditorFlags.NavigationStatic); break; } case "obstacle": { float xmin = 0.0f, xmax = 0.0f, ymin = 0.0f, ymax = 0.0f, zmin = 0.0f, zmax = 0.0f; while (reader.Read() && reader.Name != "obstacle") { switch (reader.Name) { case "xmin": xmin = reader.ReadElementContentAsFloat(); break; case "xmax": xmax = reader.ReadElementContentAsFloat(); break; case "ymin": ymin = reader.ReadElementContentAsFloat(); break; case "ymax": ymax = reader.ReadElementContentAsFloat(); break; case "zmin": zmin = reader.ReadElementContentAsFloat(); break; case "zmax": zmax = reader.ReadElementContentAsFloat(); break; } } GameObject obstacle = PrefabUtility.InstantiatePrefab(cube) as GameObject; obstacle.name = "Obstacle"; obstacle.transform.position = new Vector3(xmax + xmin, ymax + ymin, zmax + zmin) / 2.0f; obstacle.transform.localScale = new Vector3(xmax - xmin, ymax - ymin, zmax - zmin); obstacle.transform.parent = building.transform; GameObjectUtility.SetStaticEditorFlags(obstacle, StaticEditorFlags.NavigationStatic); break; } case "circleObstacle": { float radius = 0.0f, height = 0.0f; float posX_circle = 0.0f, posY_circle = 0.0f, posZ_circle = 0.0f; while (reader.Read() && reader.Name != "circleObstacle") { switch (reader.Name) { case "radius": radius = reader.ReadElementContentAsFloat(); break; case "height": height = reader.ReadElementContentAsFloat(); break; case "position": while (reader.Read() && reader.Name != "position") { switch (reader.Name) { case "x": posX_circle = reader.ReadElementContentAsFloat(); break; case "y": posY_circle = reader.ReadElementContentAsFloat(); break; case "z": posZ_circle = reader.ReadElementContentAsFloat(); break; } } break; } } GameObject circleObstacle = PrefabUtility.InstantiatePrefab(cylinder) as GameObject; circleObstacle.name = "Circle Obstacle"; circleObstacle.transform.position = new Vector3(posX_circle, posY_circle + height / 2.0f, posZ_circle); circleObstacle.transform.localScale = new Vector3(radius, height / 2.0f, radius); circleObstacle.transform.parent = building.transform; GameObjectUtility.SetStaticEditorFlags(circleObstacle, StaticEditorFlags.NavigationStatic); break; } } } //NavMeshBuilder.BuildNavMesh(); }
protected void LoadPosition(XmlReader reader) { reader.ReadToFollowing ("Position"); reader.ReadToDescendant ("x"); Vector3 loadedPosition = new Vector3 (); loadedPosition.x = reader.ReadElementContentAsFloat (); reader.ReadToNextSibling ("y"); loadedPosition.y = reader.ReadElementContentAsFloat (); reader.ReadToNextSibling ("z"); loadedPosition.z = reader.ReadElementContentAsFloat (); transform.position = loadedPosition; reader.ReadEndElement (); }