public void Load(ref XmlReader reader) { print ("Loading Piece"); float tempX = -1; float tempY = -1; float tempZ = -1; print ("Loading Piece"); while(reader.NodeType != XmlNodeType.EndElement){ reader.Read (); if (reader.Name == "Texture"){ while(reader.NodeType != XmlNodeType.EndElement){ reader.Read (); if(reader.NodeType == XmlNodeType.Text){ //texture.name = reader.Value; } } //texture.name = reader.Value; print ("Loading texture"); } reader.Read(); if (reader.Name == "Direction"){ while(reader.NodeType != XmlNodeType.EndElement){ reader.Read (); if(reader.NodeType == XmlNodeType.Text){ direction = reader.Value; } } print ("Loading direction"); } reader.Read(); if (reader.Name == "Type"){ while(reader.NodeType != XmlNodeType.EndElement){ reader.Read (); if(reader.NodeType == XmlNodeType.Text){ type = reader.Value; } } print ("Loading type"); } reader.Read(); if(reader.Name == "Moves"){ while(reader.NodeType != XmlNodeType.EndElement) { reader.Read(); } } } }
internal XDeclaration(XmlReader r) { _version = r.GetAttribute("version"); _encoding = r.GetAttribute("encoding"); _standalone = r.GetAttribute("standalone"); r.Read(); }
protected void UploadButton_Click(object sender, EventArgs e) { var path = @"C:\Temp\Upload"; if (FileUpload.HasFile) { var filename = FileUpload.FileName; path += filename; FileUpload.SaveAs(path); UploadStatusLabel.Text = "File saved as " + filename; var reader = new XmlReader(); string orderXml = reader.Read(path); var parser = new OrderParser(); var orderItems = parser.Parse(orderXml); GridView.DataSource = new List<Order>(orderItems); GridView.DataBind(); } else { UploadStatusLabel.Text = "You did not specify a file to upload."; } }
/// <summary> /// Parse an OfflineList XML DAT and return all found games and roms within /// </summary> /// <param name="filename">Name of the file to be parsed</param> /// <param name="indexId">Index ID for the DAT</param> /// <param name="keep">True if full pathnames are to be kept, false otherwise (default)</param> /// <param name="throwOnError">True if the error that is thrown should be thrown back to the caller, false otherwise</param> protected override void ParseFile(string filename, int indexId, bool keep, bool throwOnError = false) { XmlReader xtr = filename.GetXmlTextReader(); // If we got a null reader, just return if (xtr == null) { return; } // Otherwise, read the file to the end try { xtr.MoveToContent(); while (!xtr.EOF) { // We only want elements if (xtr.NodeType != XmlNodeType.Element) { xtr.Read(); continue; } switch (xtr.Name) { case "configuration": ReadConfiguration(xtr.ReadSubtree(), keep); // Skip the configuration node now that we've processed it xtr.Skip(); break; case "games": ReadGames(xtr.ReadSubtree(), filename, indexId); // Skip the games node now that we've processed it xtr.Skip(); break; default: xtr.Read(); break; } } } catch (Exception ex) { logger.Warning(ex, $"Exception found while parsing '{filename}'"); if (throwOnError) { xtr.Dispose(); throw ex; } // For XML errors, just skip the affected node xtr?.Read(); } xtr.Dispose(); }
private bool _NextToken(XmlReader reader) { while (!reader.EOF && reader.Read() && !reader.IsStartElement()) ; return !reader.EOF; }
// Use this for initialization void Start() { string last_element = ""; int counter = 1; textAsset = (TextAsset) Resources.Load("XMLs/tea_dialog"); reader = XmlReader.Create(new StringReader(textAsset.text)); //pull in the animation names from the xml file while (reader.Read ()) { if(reader.NodeType == XmlNodeType.Element){ while(reader.MoveToNextAttribute()) { if(reader.Name == "id") { //print (counter + " : " + reader.Value); animIndices.Add (counter, reader.Value); counter += 1; } } } } //print out hash table, for testing purposes //printHashTable (); }
public void OnSkillOver(GameObject gobject) { onOver = true; XmlReader xr = new XmlReader(); var name = gobject.GetComponentInParent<Skill>().name; int item = int.Parse(gobject.name) - 1; info = xr.Read(xr.LoadFile("SkillsDescription"), name, item); }
internal XDocumentType(XmlReader r) { _name = r.Name; _publicId = r.GetAttribute("PUBLIC"); _systemId = r.GetAttribute("SYSTEM"); _internalSubset = r.Value; r.Read(); }
/// <inheritdoc/> public override void ParseFile(string filename, int indexId, bool keep, bool statsOnly = false, bool throwOnError = false) { // Prepare all internal variables XmlReader xtr = XmlReader.Create(filename, new XmlReaderSettings { CheckCharacters = false, DtdProcessing = DtdProcessing.Ignore, IgnoreComments = true, IgnoreWhitespace = true, ValidationFlags = XmlSchemaValidationFlags.None, ValidationType = ValidationType.None, }); // If we got a null reader, just return if (xtr == null) { return; } // Otherwise, read the file to the end try { xtr.MoveToContent(); while (!xtr.EOF) { // We only want elements if (xtr.NodeType != XmlNodeType.Element) { xtr.Read(); continue; } switch (xtr.Name) { case "files": ReadFiles(xtr.ReadSubtree(), statsOnly, filename, indexId, keep); // Skip the machine now that we've processed it xtr.Skip(); break; default: xtr.Read(); break; } } } catch (Exception ex) when(!throwOnError) { logger.Warning(ex, $"Exception found while parsing '{filename}'"); // For XML errors, just skip the affected node xtr?.Read(); } xtr.Dispose(); }
public static void PrintNodesCore (XmlReader reader, Action onNode) { int count = 0; while (reader.Read()) { count += 1; onNode(); } Console.WriteLine("// {0} node(s)", count); }
public override object ReadObject(XmlReader reader) { ArrayOfLoanStateCompositeType ArrayOfLoanStateCompositeTypeField = null; if (IsParentStartElement(reader, false, true)) { ArrayOfLoanStateCompositeTypeField = new ArrayOfLoanStateCompositeType(); reader.Read(); LoanStateCompositeTypeDataContractSerializer LoanStateCompositeTypeDCS = new LoanStateCompositeTypeDataContractSerializer("LoanStateCompositeType", "http://schemas.datacontract.org/2004/07/", "http://schemas.datacontract.org/2004/07/"); System.Collections.ArrayList LoanStateCompositeType_List = new System.Collections.ArrayList(); for (int i = 0; (i > -1); i = (i + 1)) { if (!IsChildStartElement(reader, "LoanStateCompositeType", false, false)) { ArrayOfLoanStateCompositeTypeField.LoanStateCompositeType = new LoanStateCompositeType[LoanStateCompositeType_List.Count]; LoanStateCompositeType_List.CopyTo(ArrayOfLoanStateCompositeTypeField.LoanStateCompositeType); break; } LoanStateCompositeType_List.Add(((LoanStateCompositeType)(LoanStateCompositeTypeDCS.ReadObject(reader)))); } reader.ReadEndElement(); } return ArrayOfLoanStateCompositeTypeField; }
public List(CreateParams parentParams, XmlReader reader) { Initialize( ); // Always get our style first mStyle = parentParams.Style; Styles.Style.ParseStyleAttributesWithDefaults(reader, ref mStyle, ref ControlStyles.mList); // check for attributes we support RectangleF bounds = new RectangleF( ); SizeF parentSize = new SizeF(parentParams.Width, parentParams.Height); ParseCommonAttribs(reader, ref parentSize, ref bounds); // Get margins and padding RectangleF padding; RectangleF margin; GetMarginsAndPadding(ref mStyle, ref parentSize, ref bounds, out margin, out padding); // apply margins to as much of the bounds as we can (bottom must be done by our parent container) ApplyImmediateMargins(ref bounds, ref margin, ref parentSize); Margin = margin; // check for border styling int borderPaddingPx = 0; if (mStyle.mBorderColor.HasValue) { BorderView.BorderColor = mStyle.mBorderColor.Value; } if (mStyle.mBorderRadius.HasValue) { BorderView.CornerRadius = mStyle.mBorderRadius.Value; } if (mStyle.mBorderWidth.HasValue) { BorderView.BorderWidth = mStyle.mBorderWidth.Value; borderPaddingPx = (int)Rock.Mobile.Graphics.Util.UnitToPx(mStyle.mBorderWidth.Value + PrivateNoteConfig.BorderPadding); } if (mStyle.mBackgroundColor.HasValue) { BorderView.BackgroundColor = mStyle.mBackgroundColor.Value; } // // convert indentation if it's a percentage float listIndentation = mStyle.mListIndention.Value; if (listIndentation < 1) { listIndentation = parentParams.Width * listIndentation; } // now calculate the available width based on padding. (Don't actually change our width) // also consider the indention amount of the list. float availableWidth = bounds.Width - padding.Left - padding.Width - listIndentation - (borderPaddingPx * 2); // parse for the desired list style. Default to Bullet if they didn't put anything. ListType = reader.GetAttribute("Type"); if (string.IsNullOrEmpty(ListType) == true) { ListType = ListTypeBullet; } // Parse Child Controls int numberedCount = 1; // don't force our alignment, borders, bullet style or indentation on children. Style style = new Style( ); style = mStyle; style.mAlignment = null; style.mListIndention = null; style.mListBullet = null; style.mBorderColor = null; style.mBorderRadius = null; style.mBorderWidth = null; bool finishedParsing = false; while (finishedParsing == false && reader.Read( )) { switch (reader.NodeType) { case XmlNodeType.Element: { // Create the prefix for this list item. string listItemPrefixStr = mStyle.mListBullet + " "; if (ListType == ListTypeNumbered) { listItemPrefixStr = numberedCount.ToString() + ". "; } NoteText textLabel = Parser.CreateNoteText(new CreateParams(this, availableWidth, parentParams.Height, ref style), listItemPrefixStr); ChildControls.Add(textLabel); // create our actual child, but throw an exception if it's anything but a ListItem. IUIControl control = Parser.TryParseControl(new CreateParams(this, availableWidth - textLabel.GetFrame().Width, parentParams.Height, ref style), reader); ListItem listItem = control as ListItem; if (listItem == null) { throw new Exception(String.Format("Only a <ListItem> may be a child of a <List>. Found element <{0}>.", control.GetType( ))); } // if it will actually use the bullet point, increment our count. if (listItem.ShouldShowBulletPoint() == true) { numberedCount++; } else { // otherwise give it a blank space, and keep our count the same. textLabel.SetText(" "); } // and finally add the actual list item. ChildControls.Add(control); break; } case XmlNodeType.EndElement: { // if we hit the end of our label, we're done. //if( reader.Name == "List" || reader.Name == "L" ) if (ElementTagMatches(reader.Name)) { finishedParsing = true; } break; } } } // layout all controls float xAdjust = bounds.X + listIndentation; float yOffset = bounds.Y + padding.Top + borderPaddingPx; //vertically they should just stack // we know each child is a NoteText followed by ListItem. So, lay them out // as: * - ListItem // * - ListItem foreach (IUIControl control in ChildControls) { // position the control control.AddOffset(xAdjust + padding.Left + borderPaddingPx, yOffset); RectangleF controlFrame = control.GetFrame( ); RectangleF controlMargin = control.GetMargin( ); // is this the item prefix? if ((control as NoteText) != null) { // and update xAdjust so the actual item starts after. xAdjust += controlFrame.Width; } else { // reset the values for the next line. xAdjust = bounds.X + listIndentation; yOffset = controlFrame.Bottom + controlMargin.Height; } } // we need to store our bounds. We cannot // calculate them on the fly because we // would lose any control defined offsets, which would throw everything off. bounds.Height = (yOffset - bounds.Y) + padding.Height + borderPaddingPx; Frame = bounds; BorderView.Frame = bounds; // store our debug frame SetDebugFrame(Frame); // sort everything ChildControls.Sort(BaseControl.Sort); }
private void Init() { try { XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreComments = true; settings.IgnoreWhitespace = true; System.IO.MemoryStream stream = new System.IO.MemoryStream(serializedManifest); reader = XmlReader.Create(stream, settings); if (reader.Read() && reader.Name == "provider") { guid = new Guid(reader.GetAttribute("guid")); name = reader.GetAttribute("name"); fileName = reader.GetAttribute("resourceFileName"); } } catch (Exception e) { Debug.Assert(false, "Exception during manifest parsing"); name = ""; error = e; } inited = true; }
/// <summary> /// Parse a openMSX softawre list XML DAT and return all found games and roms within /// </summary> /// <param name="filename">Name of the file to be parsed</param> /// <param name="sysid">System ID for the DAT</param> /// <param name="srcid">Source ID for the DAT</param> /// <param name="keep">True if full pathnames are to be kept, false otherwise (default)</param> /// <param name="clean">True if game names are sanitized, false otherwise (default)</param> /// <param name="remUnicode">True if we should remove non-ASCII characters from output, false otherwise (default)</param> /// <remarks> /// </remarks> public override void ParseFile( // Standard Dat parsing string filename, int sysid, int srcid, // Miscellaneous bool keep, bool clean, bool remUnicode) { // Prepare all internal variables Encoding enc = Utilities.GetEncoding(filename); XmlReader xtr = Utilities.GetXmlTextReader(filename); // If we got a null reader, just return if (xtr == null) { return; } // Otherwise, read the file to the end try { xtr.MoveToContent(); while (!xtr.EOF) { // We only want elements if (xtr.NodeType != XmlNodeType.Element) { xtr.Read(); continue; } switch (xtr.Name) { case "softwaredb": Name = (String.IsNullOrWhiteSpace(Name) ? "openMSX Software List" : Name); Description = (String.IsNullOrWhiteSpace(Description) ? Name : Name); // string timestamp = xtr.GetAttribute("timestamp"); // CDATA xtr.Read(); break; // We want to process the entire subtree of the software case "software": ReadSoftware(xtr.ReadSubtree(), filename, sysid, srcid, keep, clean, remUnicode); // Skip the software now that we've processed it xtr.Skip(); break; default: xtr.Read(); break; } } } catch (Exception ex) { Globals.Logger.Warning("Exception found while parsing '{0}': {1}", filename, ex); // For XML errors, just skip the affected node xtr?.Read(); } xtr.Dispose(); }
/// <summary> /// Perform docking element specific actions for loading a child xml. /// </summary> /// <param name="xmlReader">Xml reader object.</param> /// <param name="pages">Collection of available pages.</param> /// <param name="child">Optional reference to existing child docking element.</param> protected override void LoadChildDockingElement(XmlReader xmlReader, KryptonPageCollection pages, IDockingElement child) { KryptonDockingManager manager = DockingManager; // Is it the expected xml element name? if (xmlReader.Name != "KP") { throw new ArgumentException("Element name 'KP' was expected but found '" + xmlReader.Name + "' instead."); } // Get the unique name of the page string uniqueName = xmlReader.GetAttribute("UN"); string boolStore = xmlReader.GetAttribute("S"); string boolVisible = xmlReader.GetAttribute("V"); KryptonPage page; // If the entry is for just a placeholder... if (CommonHelper.StringToBool(boolStore)) { // Recreate the requested store page and append page = new KryptonStorePage(uniqueName, "AutoHiddenGroup"); AutoHiddenGroupControl.Pages.Add(page); } else { // Can we find a provided page to match the incoming layout? page = pages[uniqueName]; if (page == null) { // Generate event so developer can create and supply the page now RecreateLoadingPageEventArgs args = new RecreateLoadingPageEventArgs(uniqueName); manager.RaiseRecreateLoadingPage(args); if (!args.Cancel) { page = args.Page; // Add recreated page to the looking dictionary if ((page != null) && (pages[page.UniqueName] == null)) { pages.Add(page); } } } if (page != null) { // Use the loaded visible state page.Visible = CommonHelper.StringToBool(boolVisible); // Create a proxy around the page and append it KryptonAutoHiddenProxyPage proxyPage = new KryptonAutoHiddenProxyPage(page); AutoHiddenGroupControl.Pages.Add(proxyPage); } } if (!xmlReader.Read()) { throw new ArgumentException("An element was expected but could not be read in."); } if (xmlReader.Name != "CPD") { throw new ArgumentException("Expected 'CPD' element was not found"); } bool finished = xmlReader.IsEmptyElement; // Generate event so custom data can be loaded and/or the page to be added can be modified DockPageLoadingEventArgs pageLoading = new DockPageLoadingEventArgs(manager, xmlReader, page); manager.RaisePageLoading(pageLoading); // Read everything until we get the end of custom data marker while (!finished) { // Check it has the expected name if (xmlReader.NodeType == XmlNodeType.EndElement) { finished = (xmlReader.Name == "CPD"); } if (!finished) { if (!xmlReader.Read()) { throw new ArgumentException("An element was expected but could not be read in."); } } } if (!xmlReader.Read()) { throw new ArgumentException("An element was expected but could not be read in."); } }
public override object ReadObject(XmlReader reader) { LoanStateCompositeType LoanStateCompositeTypeField = null; if (IsParentStartElement(reader, false, true)) { LoanStateCompositeTypeField = new LoanStateCompositeType(); reader.Read(); if (IsChildStartElement(reader, "BookID", false, false)) { reader.Read(); LoanStateCompositeTypeField.BookID = XmlConvert.ToInt32(reader.ReadString()); reader.ReadEndElement(); } if (IsChildStartElement(reader, "Description", true, false)) { reader.Read(); LoanStateCompositeTypeField.Description = reader.ReadString(); reader.ReadEndElement(); } if (IsChildStartElement(reader, "ISBN", true, false)) { reader.Read(); LoanStateCompositeTypeField.ISBN = reader.ReadString(); reader.ReadEndElement(); } if (IsChildStartElement(reader, "Language", true, false)) { reader.Read(); LoanStateCompositeTypeField.Language = reader.ReadString(); reader.ReadEndElement(); } if (IsChildStartElement(reader, "LoanExpirationDate", false, false)) { reader.Read(); // LoanStateCompositeTypeField.LoanExpirationDate = XmlConvert.ToDateTime(reader.ReadString()); LoanStateCompositeTypeField.LoanExpirationDate = LibraryTerminal.Utils.Parse(reader.ReadString()); reader.ReadEndElement(); } if (IsChildStartElement(reader, "LoanStartDate", false, false)) { reader.Read(); // LoanStateCompositeTypeField.LoanStartDate = XmlConvert.ToDateTime(reader.ReadString()); LoanStateCompositeTypeField.LoanStartDate = LibraryTerminal.Utils.Parse(reader.ReadString()); reader.ReadEndElement(); } if (IsChildStartElement(reader, "PublicationDate", false, false)) { reader.Read(); // LoanStateCompositeTypeField.PublicationDate = XmlConvert.ToDateTime(reader.ReadString()); LoanStateCompositeTypeField.PublicationDate = LibraryTerminal.Utils.Parse(reader.ReadString()); reader.ReadEndElement(); } if (IsChildStartElement(reader, "Publisher", true, false)) { reader.Read(); LoanStateCompositeTypeField.Publisher = reader.ReadString(); reader.ReadEndElement(); } if (IsChildStartElement(reader, "Title", true, false)) { reader.Read(); LoanStateCompositeTypeField.Title = reader.ReadString(); reader.ReadEndElement(); } reader.ReadEndElement(); } return LoanStateCompositeTypeField; }
private void ParseVulnerabilityInfoFromWassp(SQLiteCommand sqliteCommand, XmlReader xmlReader) { try { while (xmlReader.Read()) { if (xmlReader.IsStartElement()) { switch (xmlReader.Name) { case "host": { sqliteCommand.Parameters.Add(new SQLiteParameter("IpAddress", xmlReader.GetAttribute("ip"))); sqliteCommand.Parameters.Add(new SQLiteParameter("HostName", xmlReader.GetAttribute("name"))); if (sqliteCommand.Parameters.Contains("HostName") && UserPrefersHostName && !string.IsNullOrWhiteSpace(sqliteCommand.Parameters["Hostname"].Value.ToString())) { sqliteCommand.Parameters.Add(new SQLiteParameter( "AssetIdToReport", sqliteCommand.Parameters["HostName"].Value)); } else { sqliteCommand.Parameters.Add(new SQLiteParameter( "AssetIdToReport", sqliteCommand.Parameters["IpAddress"].Value)); } InsertAssetCommand(sqliteCommand); break; } case "test": { sqliteCommand.Parameters.Add(new SQLiteParameter("VulnId", xmlReader.GetAttribute("id"))); break; } case "check": { sqliteCommand.Parameters.Add(new SQLiteParameter("VulnTitle", ObtainXmlReaderValue(xmlReader))); break; } case "description": { sqliteCommand.Parameters.Add(new SQLiteParameter("Description", ObtainXmlReaderValue(xmlReader))); break; } case "vulnerability": { xmlReader.Read(); sqliteCommand.Parameters.Add(new SQLiteParameter("Impact", xmlReader.Value)); sqliteCommand.Parameters.Add(new SQLiteParameter("RawRisk", ConvertImpactToRawRisk(xmlReader.Value))); break; } case "control": { switch (xmlReader.GetAttribute("regulation")) { case "NIST": { xmlReader.Read(); if (!sqliteCommand.Parameters.Contains("NistControl")) { sqliteCommand.Parameters.Add(new SQLiteParameter("NistControl", xmlReader.Value)); } else { sqliteCommand.Parameters["NistControl"].Value = sqliteCommand.Parameters["NistControl"].Value + Environment.NewLine + xmlReader.Value; } break; } case "DOD": { xmlReader.Read(); if (!sqliteCommand.Parameters.Contains("IaControl")) { sqliteCommand.Parameters.Add(new SQLiteParameter("IaControl", xmlReader.Value)); } else { sqliteCommand.Parameters["IaControl"].Value = sqliteCommand.Parameters["IaControl"].Value + Environment.NewLine + xmlReader.Value; } break; } default: { break; } } break; } case "result": { sqliteCommand.Parameters.Add(new SQLiteParameter("Status", ConvertTestResultToStatus(ObtainXmlReaderValue(xmlReader)))); break; } case "recommendation": { sqliteCommand.Parameters.Add(new SQLiteParameter("FixText", ObtainXmlReaderValue(xmlReader))); break; } default: { break; } } } else if (xmlReader.NodeType == XmlNodeType.EndElement && xmlReader.Name.Equals("test")) { InsertVulnerabilityCommand(sqliteCommand); sqliteCommand.CommandText = SetSqliteCommandText("UniqueFinding"); sqliteCommand.ExecuteNonQuery(); } } } catch (Exception exception) { log.Error("Unable to parse vulnerability information."); throw exception; } }
private void AddImages(List <RemoteImageInfo> list, bool isConsole, XmlReader reader, CancellationToken cancellationToken) { reader.MoveToContent(); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { switch (reader.Name) { case "fanart": { using (var subReader = reader.ReadSubtree()) { PopulateImageCategory(list, subReader, cancellationToken, ImageType.Backdrop); } break; } case "screenshot": { using (var subReader = reader.ReadSubtree()) { PopulateImageCategory(list, subReader, cancellationToken, ImageType.Screenshot); } break; } case "boxart": { var side = reader.GetAttribute("side"); if (side == null) { break; } if (side.Equals("front", StringComparison.InvariantCultureIgnoreCase)) { PopulateImage(list, reader, cancellationToken, ImageType.Primary); } else if (side.Equals("back", StringComparison.InvariantCultureIgnoreCase)) { // Have to account for console primary images being uploaded as side-back PopulateImage(list, reader, cancellationToken, isConsole ? ImageType.Primary : ImageType.BoxRear); } break; } case "banner": { PopulateImage(list, reader, cancellationToken, ImageType.Banner); break; } case "clearlogo": { PopulateImage(list, reader, cancellationToken, ImageType.Logo); break; } default: { using (reader.ReadSubtree()) { } break; } } } } }
public override object ReadObject(XmlReader reader) { BookCompositeType BookCompositeTypeField = null; if (IsParentStartElement(reader, false, true)) { BookCompositeTypeField = new BookCompositeType(); reader.Read(); schemas.microsoft.com.Serialization.Arrays.ArrayOfstringDataContractSerializer AuthorsDCS = new schemas.microsoft.com.Serialization.Arrays.ArrayOfstringDataContractSerializer("Authors", "http://schemas.datacontract.org/2004/07/", "http://schemas.microsoft.com/2003/10/Serialization/Arrays"); AuthorsDCS.BodyParts = this.BodyParts; BookCompositeTypeField.Authors = ((schemas.microsoft.com.Serialization.Arrays.ArrayOfstring)(AuthorsDCS.ReadObject(reader))); if (IsChildStartElement(reader, "Description", true, false)) { reader.Read(); BookCompositeTypeField.Description = reader.ReadString(); reader.ReadEndElement(); } if (IsChildStartElement(reader, "ID", false, false)) { reader.Read(); BookCompositeTypeField.ID = XmlConvert.ToInt32(reader.ReadString()); reader.ReadEndElement(); } if (IsChildStartElement(reader, "ISBN", true, false)) { reader.Read(); BookCompositeTypeField.ISBN = reader.ReadString(); reader.ReadEndElement(); } if (IsChildStartElement(reader, "Language", true, false)) { reader.Read(); BookCompositeTypeField.Language = reader.ReadString(); reader.ReadEndElement(); } if (IsChildStartElement(reader, "PublicationDate", false, false)) { reader.Read(); //BookCompositeTypeField.PublicationDate = XmlConvert.ToDateTime(reader.ReadString()); BookCompositeTypeField.PublicationDate = LibraryTerminal.Utils.Parse(reader.ReadString()); reader.ReadEndElement(); } if (IsChildStartElement(reader, "Publisher", true, false)) { reader.Read(); BookCompositeTypeField.Publisher = reader.ReadString(); reader.ReadEndElement(); } schemas.microsoft.com.Serialization.Arrays.ArrayOfstringDataContractSerializer SubjectsDCS = new schemas.microsoft.com.Serialization.Arrays.ArrayOfstringDataContractSerializer("Subjects", "http://schemas.datacontract.org/2004/07/", "http://schemas.microsoft.com/2003/10/Serialization/Arrays"); SubjectsDCS.BodyParts = this.BodyParts; BookCompositeTypeField.Subjects = ((schemas.microsoft.com.Serialization.Arrays.ArrayOfstring)(SubjectsDCS.ReadObject(reader))); if (IsChildStartElement(reader, "Title", true, false)) { reader.Read(); BookCompositeTypeField.Title = reader.ReadString(); reader.ReadEndElement(); } reader.ReadEndElement(); } return BookCompositeTypeField; }
/// <summary> /// Parse an SabreDat XML DAT and return all found directories and files within /// </summary> /// <param name="filename">Name of the file to be parsed</param> /// <param name="indexId">Index ID for the DAT</param> /// <param name="keep">True if full pathnames are to be kept, false otherwise (default)</param> /// <param name="throwOnError">True if the error that is thrown should be thrown back to the caller, false otherwise</param> protected override void ParseFile(string filename, int indexId, bool keep, bool throwOnError = false) { // Prepare all internal variables XmlReader xtr = filename.GetXmlTextReader(); // If we got a null reader, just return if (xtr == null) { return; } // Otherwise, read the file to the end try { xtr.MoveToContent(); while (!xtr.EOF) { // We only want elements if (xtr.NodeType != XmlNodeType.Element) { xtr.Read(); continue; } switch (xtr.Name) { case "header": XmlSerializer xs = new XmlSerializer(typeof(DatHeader)); DatHeader header = xs.Deserialize(xtr.ReadSubtree()) as DatHeader; Header.ConditionalCopy(header); xtr.Skip(); break; case "directory": ReadDirectory(xtr.ReadSubtree(), filename, indexId); // Skip the directory node now that we've processed it xtr.Read(); break; default: xtr.Read(); break; } } } catch (Exception ex) { logger.Warning(ex, $"Exception found while parsing '{filename}'"); if (throwOnError) { xtr.Dispose(); throw ex; } // For XML errors, just skip the affected node xtr?.Read(); } xtr.Dispose(); }
static void Parse() { string XmlFilePath = "Assets/Resources/revit.xml"; string text = File.ReadAllText(XmlFilePath); text = text.Replace("><", "> <"); File.WriteAllText(XmlFilePath, text); XmlReader reader = XmlReader.Create(XmlFilePath); GameObject agentArea = new GameObject("agentArea"); AgentAreaDef agentAreaDef = agentArea.AddComponent <AgentAreaDef>(); reader.ReadToFollowing("worldBounds"); while (reader.Read()) { switch (reader.Name) { case "agentRegion": { int numAgents = 1; float xmin = 0.0f, xmax = 0.0f, ymin = 0.0f, ymax = 0.0f, zmin = 0.0f, zmax = 0.0f; float x = 0.0f, y = 0.0f, z = 0.0f; while (reader.Read() && reader.Name != "agentRegion") { switch (reader.Name) { case "numAgents": numAgents = reader.ReadElementContentAsInt(); break; 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; case "targetLocation": while (reader.Read() && reader.Name != "targetLocation") { switch (reader.Name) { case "x": x = reader.ReadElementContentAsFloat(); break; case "y": y = reader.ReadElementContentAsFloat(); break; case "z": z = reader.ReadElementContentAsFloat(); break; } } break; } } agentAreaDef.agentArea.Add(new float[] { xmin, xmax, zmin, zmax }); agentAreaDef.weight.Add(numAgents); agentAreaDef.agentAmount = 100; break; } } } Debug.Log(agentAreaDef.weight.Count.ToString()); }
/// @brief Load a plugin from File. /// @note This method take care of update change state of the window. /// @todo Correct method to implement new plugin system. public bool OpenFile(string FileName, bool displayErrors) { XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreComments = true; settings.IgnoreProcessingInstructions = true; settings.IgnoreWhitespace = true; XmlReader tr = XmlReader.Create(FileName, settings); bool ReadText = false; if (referencesList.Items.Count > 0) { referencesList.Items.Clear(); //clear out the reference list } try { while (tr.Read()) { if (tr.NodeType == XmlNodeType.Text && ReadText) { //set or reset font and color codeEditorView.SelectAll(); codeEditorView.SelectionFont = this.defaultFont; codeEditorView.SelectionColor = Color.Black; codeEditorView.Text = tr.Value; ReadText = false; } switch (tr.Name.ToLower()) { case "reference": if (!tr.IsEmptyElement) //prevent empty element generates error { referencesList.Items.Add(tr.GetAttribute("name")); } break; case "instance": instanceName.Text = tr.GetAttribute("class"); break; case "code": ReadText = true; break; } } m_SaveFileName = FileName; CodeChanged = false; if (displayErrors) { errorListView.Items.Clear(); ModuleCompiler.EnumerateErrors(EnumErrors); } return(true); } catch (IOException ioe) { MessageBox.Show(this, ioe.Message, "Failed to load plug-in", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(false); } catch (XmlException xmle) { MessageBox.Show(this, xmle.Message, "Failed to load plug-in", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(false); } finally { tr.Close(); } }
static INode ReadNode(XmlReader reader, bool nested = false) { var skipFirstRead = nested; Debug.Assert(reader.NodeType == XmlNodeType.Element); var name = reader.Name; List <INode> nodes = new List <INode>(); INode node = null; while (skipFirstRead || reader.Read()) { skipFirstRead = false; switch (reader.NodeType) { case XmlNodeType.EndElement: Debug.Assert(reader.Name == name); if (nodes.Count == 0) //Empty element { return(null); } if (nodes.Count == 1) { return(nodes[0]); } return(new ListNode(nodes, (IXmlNamespaceResolver)reader, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition)); case XmlNodeType.Element: var isEmpty = reader.IsEmptyElement && reader.Name == name; var elementName = reader.Name; var elementNsUri = reader.NamespaceURI; var elementXmlInfo = (IXmlLineInfo)reader; IList <KeyValuePair <string, string> > xmlns; var attributes = ParseXamlAttributes(reader, out xmlns); var prefixes = PrefixesToIgnore(xmlns); IList <XmlType> typeArguments = null; if (attributes.Any(kvp => kvp.Key == XmlName.xTypeArguments)) { typeArguments = ((ValueNode)attributes.First(kvp => kvp.Key == XmlName.xTypeArguments).Value).Value as IList <XmlType>; } node = new ElementNode(new XmlType(elementNsUri, elementName, typeArguments), elementNsUri, reader as IXmlNamespaceResolver, elementXmlInfo.LineNumber, elementXmlInfo.LinePosition); ((IElementNode)node).Properties.AddRange(attributes); (node.IgnorablePrefixes ?? (node.IgnorablePrefixes = new List <string>()))?.AddRange(prefixes); ParseXamlElementFor((IElementNode)node, reader); nodes.Add(node); if (isEmpty || nested) { return(node); } break; case XmlNodeType.Text: node = new ValueNode(reader.Value.Trim(), (IXmlNamespaceResolver)reader, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); nodes.Add(node); break; case XmlNodeType.Whitespace: break; default: Debug.WriteLine("Unhandled node {0} {1} {2}", reader.NodeType, reader.Name, reader.Value); break; } } throw new XamlParseException("Closing PropertyElement expected", (IXmlLineInfo)reader); }
public void ReadXmlPrototype(XmlReader readerParent) { ObjectType = readerParent.GetAttribute("objectType"); XmlReader reader = readerParent.ReadSubtree(); while (reader.Read()) { switch (reader.Name) { case "Name": reader.Read(); Name = reader.ReadContentAsString(); break; case "TypeTag": reader.Read(); typeTags.Add(reader.ReadContentAsString()); break; case "Description": reader.Read(); description = reader.ReadContentAsString(); break; case "MovementCost": reader.Read(); MovementCost = reader.ReadContentAsFloat(); break; case "PathfindingModifier": reader.Read(); PathfindingModifier = reader.ReadContentAsFloat(); break; case "PathfindingWeight": reader.Read(); PathfindingWeight = reader.ReadContentAsFloat(); break; case "Width": reader.Read(); Width = reader.ReadContentAsInt(); break; case "Height": reader.Read(); Height = reader.ReadContentAsInt(); break; case "LinksToNeighbours": reader.Read(); LinksToNeighbour = reader.ReadContentAsBoolean(); break; case "EnclosesRooms": reader.Read(); RoomEnclosure = reader.ReadContentAsBoolean(); break; case "CanReplaceFurniture": replaceableFurniture.Add(reader.GetAttribute("typeTag").ToString()); break; case "DragType": reader.Read(); DragType = reader.ReadContentAsString(); break; case "BuildingJob": float jobTime = float.Parse(reader.GetAttribute("jobTime")); List <Inventory> invs = new List <Inventory>(); XmlReader inventoryReader = reader.ReadSubtree(); while (inventoryReader.Read()) { if (inventoryReader.Name == "Inventory") { // Found an inventory requirement, so add it to the list! invs.Add(new Inventory( inventoryReader.GetAttribute("objectType"), int.Parse(inventoryReader.GetAttribute("amount")), 0)); } } Job j = new Job( null, ObjectType, FurnitureActions.JobComplete_FurnitureBuilding, jobTime, invs.ToArray(), Job.JobPriority.High); j.JobDescription = "job_build_" + ObjectType + "_desc"; PrototypeManager.FurnitureJob.SetPrototype(ObjectType, j); break; case "CanBeBuiltOn": TileType tileType = TileType.GetTileType(reader.GetAttribute("tileType")); tileTypeBuildPermissions.Add(tileType); break; case "Action": XmlReader subtree = reader.ReadSubtree(); EventActions.ReadXml(subtree); subtree.Close(); break; case "ContextMenuAction": contextMenuLuaActions.Add(new ContextMenuLuaAction { LuaFunction = reader.GetAttribute("FunctionName"), Text = reader.GetAttribute("Text"), RequiereCharacterSelected = bool.Parse(reader.GetAttribute("RequiereCharacterSelected")) }); break; case "IsEnterable": isEnterableAction = reader.GetAttribute("FunctionName"); break; case "GetSpriteName": getSpriteNameAction = reader.GetAttribute("FunctionName"); break; case "JobSpotOffset": JobSpotOffset = new Vector2( int.Parse(reader.GetAttribute("X")), int.Parse(reader.GetAttribute("Y"))); break; case "JobSpawnSpotOffset": jobSpawnSpotOffset = new Vector2( int.Parse(reader.GetAttribute("X")), int.Parse(reader.GetAttribute("Y"))); break; case "PowerConnection": PowerConnection = new Connection(); PowerConnection.ReadPrototype(reader); break; case "Params": ReadXmlParams(reader); // Read in the Param tag break; case "LocalizationCode": reader.Read(); LocalizationCode = reader.ReadContentAsString(); break; case "UnlocalizedDescription": reader.Read(); UnlocalizedDescription = reader.ReadContentAsString(); break; } } }
private static void readRelationSubtree(XmlReader subtree, List<OsmRelationMember> members, List<OsmTag> tags) { while (subtree.Read ()) { switch (subtree.Name) { case "member": EntityType type = EntityTypeMethods.fromString (subtree ["type"]); members.Add (new OsmRelationMember (long.Parse (subtree ["ref"]), type, subtree ["role"])); break; case "tag": tags.Add (new OsmTag (subtree ["k"], subtree ["v"])); break; } } }
public override object ReadObject(XmlReader reader) { UserCompositeType UserCompositeTypeField = null; if (IsParentStartElement(reader, false, true)) { UserCompositeTypeField = new UserCompositeType(); reader.Read(); if (IsChildStartElement(reader, "Delay", false, false)) { reader.Read(); UserCompositeTypeField.Delay = XmlConvert.ToBoolean(reader.ReadString()); reader.ReadEndElement(); } if (IsChildStartElement(reader, "FirstName", true, false)) { reader.Read(); UserCompositeTypeField.FirstName = reader.ReadString(); reader.ReadEndElement(); } if (IsChildStartElement(reader, "ID", false, false)) { reader.Read(); UserCompositeTypeField.ID = XmlConvert.ToInt32(reader.ReadString()); reader.ReadEndElement(); } if (IsChildStartElement(reader, "LastName", true, false)) { reader.Read(); UserCompositeTypeField.LastName = reader.ReadString(); reader.ReadEndElement(); } if (IsChildStartElement(reader, "MaxLoansReached", false, false)) { reader.Read(); UserCompositeTypeField.MaxLoansReached = XmlConvert.ToBoolean(reader.ReadString()); reader.ReadEndElement(); } reader.ReadEndElement(); } return UserCompositeTypeField; }
static void Main() { Console.Write("Running ..."); StringBuilder output = new StringBuilder(); Boolean insideNameNode = false; int pointSetCount = 1; string prevKmlObjName = string.Empty; output.AppendLine("function AddParsedGeoRegions(){ "); // Create an XML reader for this file. using (XmlReader reader = XmlReader.Create("app2-test5.kml")) { List <string> kmlObjectNamesToGet = new List <string>(); List <string> kmlObjectNames = new List <string>(); string kmlObjectName = string.Empty; string kmlObjectCoords = string.Empty; var kmlObject = new List <KmlObject>(); bool ignoreThisGrouping = false; bool insidePlacemark = false; kmlObjectNamesToGet.Add("mexico"); while (reader.Read()) { // Only detect start elements. if (reader.IsStartElement()) { // Get element name and switch on it. switch (reader.Name) { case "Placemark": //insidePlacemark = true; break; case "name": if (reader.Read() && insidePlacemark) { kmlObjectName = reader.Value.Trim().ToLower(); kmlObjectName = kmlObjectName.Replace(" ", "_"); kmlObjectName = kmlObjectName.Replace("&", ""); kmlObjectName = kmlObjectName.Replace("__", "_"); kmlObjectName = kmlObjectName.Replace("(", ""); kmlObjectName = kmlObjectName.Replace(")", ""); kmlObjectName = kmlObjectName.Replace(".", ""); kmlObjectName = kmlObjectName.Replace(",", ""); kmlObjectName = kmlObjectName.Replace("'", ""); kmlObjectName = kmlObjectName.Replace(">", ""); kmlObjectName = kmlObjectName.Replace("<", ""); kmlObjectNames.Add(kmlObjectName); } break; case "Data": // Search for the attribute name on this current node. string attribute = reader["name"]; if (attribute != null) { insideNameNode = attribute == "NAME" || attribute == "Country"; } break; case "value": if (insideNameNode) { if (reader.Read()) { kmlObjectName = reader.Value.Trim().ToLower(); //Console.WriteLine("name: " + kmlObjectName); //output.AppendLine(" name: " + reader.Value.Trim()); kmlObjectName = kmlObjectName.Replace(" ", "_"); kmlObjectName = kmlObjectName.Replace("&", ""); kmlObjectName = kmlObjectName.Replace("__", "_"); kmlObjectName = kmlObjectName.Replace("(", ""); kmlObjectName = kmlObjectName.Replace(")", ""); kmlObjectName = kmlObjectName.Replace(".", ""); kmlObjectName = kmlObjectName.Replace(",", ""); kmlObjectName = kmlObjectName.Replace("'", ""); kmlObjectName = kmlObjectName.Replace(">", ""); kmlObjectName = kmlObjectName.Replace("<", ""); kmlObjectNames.Add(kmlObjectName); //kmlObject.Add(new KmlObject { CoordSetCount = 0, Name = kmlObjectName }); //output.AppendLine(" //" + kmlObjectName); //output.AppendLine(" var " + kmlObjectName + "_points = []; "); insideNameNode = false; //if (kmlObjectNamesToGet.Contains(kmlObjectName)) //{ // //proceed // ignoreThisGrouping = false; //} //else //{ // //do not do anything with it // ignoreThisGrouping = true; //} } } break; case "coordinates": //if (ignoreThisGrouping) //{ // break; //} //Console.WriteLine("Start <coordinates> element."); //output.AppendLine("Start <coordinates> element."); if (reader.Read()) { kmlObjectCoords = reader.Value.Trim(); //Console.WriteLine("coordinates for "+kmlObjectName+" : " + kmlObjectCoords); //output.AppendLine("coordinates for " + kmlObjectName + " : " + kmlObjectCoords); string[] split = kmlObjectCoords.Split(new Char[] { ' ' }); string[] realCoords = new string[split.Length]; if (kmlObjectName == prevKmlObjName) { //iterate point set count pointSetCount++; } else { //kmlObjectPointSets.Add(pointSetCount); Console.WriteLine(" [DEBUG]: pointsetcount=" + pointSetCount + " for " + kmlObjectName); //Console.ReadLine(); kmlObject.Add(new KmlObject { CoordSetCount = pointSetCount, Name = kmlObjectName }); //reset point set count pointSetCount = 1; prevKmlObjName = kmlObjectName; } output.AppendLine(" //" + kmlObjectName); output.AppendLine(" var " + kmlObjectName + "_pointset_" + pointSetCount + " = [ "); for (int j = 0; j < split.Length; j++) { string[] split2 = split[j].Split(new Char[] { ',' }); //Console.WriteLine(split2[1] + "," + split2[0]); realCoords[j] = split2[1] + "," + split2[0]; //Console.WriteLine(kmlObjectName + ": " + realCoords[j]); output.AppendLine(" new google.maps.LatLng( " + realCoords[j] + " ), "); } output.AppendLine(" ]; "); output.AppendLine(""); //Console.Write("."); } break; } } } //for (int i = 0; i < kmlObject.Count; i++) //{ // int containsCount = 0; // if (kmlObject[i].Name.Contains(kmlObjectNames[i])) // { // containsCount++; // if (containsCount > 1) // { // Console.WriteLine("duplicate: " + kmlObjectNames[i]); // Console.ReadLine(); // } // } //} //for (int i = 0; i < kmlObjectNames.Count; i++) //{ // //see if each name is in the kmlobj and how many times is it in there //} //when we are done if ((kmlObject.Count == kmlObjectNames.Count) && kmlObject.Count > 0) { for (int i = 0; i < kmlObject.Count; i++) { //kmlObject[i].Name = kmlObject[(i + 1)].Name; if (i == (kmlObject.Count - 1)) { //kmlObject[i].CoordSetCount = kmlObject[(i + 1)].CoordSetCount; } else { kmlObject[i].CoordSetCount = kmlObject[(i + 1)].CoordSetCount; } } kmlObject.RemoveAt((kmlObjectNames.Count - 1)); kmlObject.Add(new KmlObject { CoordSetCount = pointSetCount, Name = kmlObjectName }); } //determine if there are any duplicates for (int i = 0; i < kmlObject.Count; i++) { int nameIsThereCount = 0; for (int j = 0; j < kmlObjectNames.Count; j++) { if (kmlObject[i].Name == kmlObjectNames[j]) { nameIsThereCount++; } } if (nameIsThereCount > 1) { //change the duplicate Console.WriteLine("duplicate: " + kmlObject[i].Name); //Console.ReadLine(); } } //for (int l = 0; l < kmlObjectPointSets.Count; l++) //{ // kmlObject.Add(new KmlObject { CoordSetCount = kmlObjectPointSets[l], Name = kmlObjectNames[l] }); //} //rearrage //kmlObject.RemoveAt(0); string[] tempA = kmlObjectNames.ToArray(); for (int j = 0; j < tempA.Length; j++) { //Console.Write("."); //Console.WriteLine(tempA[j]); output.AppendLine(" //contruct the polygon "); output.AppendLine(" var " + tempA[j] + "_polygon = new google.maps.Polygon({ "); if (kmlObject[j].Name == tempA[j] && kmlObject[j].CoordSetCount > 1) { //string[] tempB = kmlObjectPointSet.ToArray(); output.AppendLine(" paths: ["); for (int k = 0; k < kmlObject[j].CoordSetCount; k++) { output.AppendLine(" " + tempA[j] + "_pointset_" + (k + 1) + ", "); //output.AppendLine(" " + tempA[j] + "_pointset_" + (k + 1) + ", "); } output.AppendLine(" ],"); } else { output.AppendLine(" paths: " + tempA[j] + "_pointset_1, "); } output.AppendLine(" strokeColor: defaultOutlineColor, "); output.AppendLine(" strokeOpacity: defaultStrokeOpacity, "); output.AppendLine(" strokeWeight: defaultStrokeWeight, "); output.AppendLine(" fillColor: defaultFillColor, "); output.AppendLine(" fillOpacity: defaultFillOpacity "); output.AppendLine(" }); "); output.AppendLine(""); output.AppendLine(" //add event listeners to polygon, then add polygon to map "); output.AppendLine(" google.maps.event.addListener(" + tempA[j] + "_polygon, 'mouseover', function() { " + tempA[j] + "_polygon.setOptions({strokeOpacity: 1, fillColor: defaultHighlightColor}); });"); output.AppendLine(" google.maps.event.addListener(" + tempA[j] + "_polygon, 'mouseout', function() { " + tempA[j] + "_polygon.setOptions({strokeOpacity: 0, fillColor: defaultFillColor}); });"); output.AppendLine(" google.maps.event.addListener(" + tempA[j] + "_polygon, 'click', function() { polygonClickedActionHandler(\"" + tempA[j] + "\"); });"); output.AppendLine(" " + tempA[j] + "_polygon.setMap(map); "); output.AppendLine(""); } output.AppendLine("} "); //output System.IO.StreamWriter outputFile = new System.IO.StreamWriter("C:\\Users\\cadetpeters89\\Documents\\CUSTOM\\projects\\git\\SobekCM-Web-Application\\SobekCM\\dev\\mapedit\\sandbox\\output.js"); outputFile.WriteLine(output); outputFile.Close(); //close output Console.Write(" Completed!"); //Console.ReadLine(); //pause } }
public string ReadString(XmlReader reader) { reader.Read(); string s = reader.ReadString(); reader.ReadEndElement(); return s; }
public override object ReadObject(XmlReader reader) { LoanCompositeType LoanCompositeTypeField = null; if (IsParentStartElement(reader, false, true)) { LoanCompositeTypeField = new LoanCompositeType(); reader.Read(); if (IsChildStartElement(reader, "BookID", false, false)) { reader.Read(); LoanCompositeTypeField.BookID = XmlConvert.ToInt32(reader.ReadString()); reader.ReadEndElement(); } if (IsChildStartElement(reader, "DeliveryDate", true, false)) { reader.Read(); //LoanCompositeTypeField.DeliveryDate = XmlConvert.ToDateTime(reader.ReadString()); LoanCompositeTypeField.DeliveryDate = LibraryTerminal.Utils.Parse(reader.ReadString()); reader.ReadEndElement(); } if (IsChildStartElement(reader, "ExpirationDate", false, false)) { reader.Read(); //LoanCompositeTypeField.ExpirationDate = XmlConvert.ToDateTime(reader.ReadString()); LoanCompositeTypeField.ExpirationDate = LibraryTerminal.Utils.Parse(reader.ReadString()); reader.ReadEndElement(); } if (IsChildStartElement(reader, "StartDate", false, false)) { reader.Read(); //LoanCompositeTypeField.StartDate = XmlConvert.ToDateTime(reader.ReadString()); LoanCompositeTypeField.StartDate = LibraryTerminal.Utils.Parse(reader.ReadString()); reader.ReadEndElement(); } if (IsChildStartElement(reader, "UserID", false, false)) { reader.Read(); LoanCompositeTypeField.UserID = XmlConvert.ToInt32(reader.ReadString()); reader.ReadEndElement(); } reader.ReadEndElement(); } return LoanCompositeTypeField; }
/// <summary> /// Parse a openMSX softawre list XML DAT and return all found games and roms within /// </summary> /// <param name="filename">Name of the file to be parsed</param> /// <param name="indexId">Index ID for the DAT</param> /// <param name="keep">True if full pathnames are to be kept, false otherwise (default)</param> /// <param name="throwOnError">True if the error that is thrown should be thrown back to the caller, false otherwise</param> protected override void ParseFile(string filename, int indexId, bool keep, bool throwOnError = false) { // Prepare all internal variables XmlReader xtr = filename.GetXmlTextReader(); // If we got a null reader, just return if (xtr == null) { return; } // Otherwise, read the file to the end try { xtr.MoveToContent(); while (!xtr.EOF) { // We only want elements if (xtr.NodeType != XmlNodeType.Element) { xtr.Read(); continue; } switch (xtr.Name) { case "softwaredb": Header.Name = Header.Name ?? "openMSX Software List"; Header.Description = Header.Description ?? Header.Name; Header.Date = Header.Date ?? xtr.GetAttribute("timestamp"); xtr.Read(); break; // We want to process the entire subtree of the software case "software": ReadSoftware(xtr.ReadSubtree(), filename, indexId); // Skip the software now that we've processed it xtr.Skip(); break; default: xtr.Read(); break; } } } catch (Exception ex) { logger.Warning(ex, $"Exception found while parsing '{filename}'"); if (throwOnError) { xtr.Dispose(); throw ex; } // For XML errors, just skip the affected node xtr?.Read(); } xtr.Dispose(); }
/// <inheritdoc/> public override void ParseFile(string filename, int indexId, bool keep, bool statsOnly = false, bool throwOnError = false) { // Prepare all internal variables XmlReader xtr = XmlReader.Create(filename, new XmlReaderSettings { CheckCharacters = false, DtdProcessing = DtdProcessing.Ignore, IgnoreComments = true, IgnoreWhitespace = true, ValidationFlags = XmlSchemaValidationFlags.None, ValidationType = ValidationType.None, }); List <string> dirs = new List <string>(); // If we got a null reader, just return if (xtr == null) { return; } // Otherwise, read the file to the end try { xtr.MoveToContent(); while (!xtr.EOF) { // We only want elements if (xtr.NodeType != XmlNodeType.Element) { // If we're ending a dir, remove the last item from the dirs list, if possible if (xtr.Name == "dir" && dirs.Count > 0) { dirs.RemoveAt(dirs.Count - 1); } xtr.Read(); continue; } switch (xtr.Name) { // The datafile tag can have some attributes case "datafile": Header.Build ??= xtr.GetAttribute("build"); Header.Debug ??= xtr.GetAttribute("debug").AsYesNo(); xtr.Read(); break; // We want to process the entire subtree of the header case "header": ReadHeader(xtr.ReadSubtree(), keep); // Skip the header node now that we've processed it xtr.Skip(); break; // Unique to RomVault-created DATs case "dir": Header.Type = "SuperDAT"; dirs.Add(xtr.GetAttribute("name") ?? string.Empty); xtr.Read(); break; // We want to process the entire subtree of the game case "machine": // New-style Logiqx case "game": // Old-style Logiqx ReadMachine(xtr.ReadSubtree(), dirs, statsOnly, filename, indexId, keep); // Skip the machine now that we've processed it xtr.Skip(); break; default: xtr.Read(); break; } } } catch (Exception ex) when(!throwOnError) { logger.Warning(ex, $"Exception found while parsing '{filename}'"); // For XML errors, just skip the affected node xtr?.Read(); } xtr.Dispose(); }
static void ParseXamlElementFor(IElementNode node, XmlReader reader) { Debug.Assert(reader.NodeType == XmlNodeType.Element); var elementName = reader.Name; var isEmpty = reader.IsEmptyElement; if (isEmpty) { return; } while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.EndElement: Debug.Assert(reader.Name == elementName); //make sure we close the right element return; case XmlNodeType.Element: // 1. Property Element. if (reader.Name.Contains(".")) { XmlName name; if (reader.Name.StartsWith(elementName + ".", StringComparison.Ordinal)) { name = new XmlName(reader.NamespaceURI, reader.Name.Substring(elementName.Length + 1)); } else //Attached DP { name = new XmlName(reader.NamespaceURI, reader.LocalName); } var prop = ReadNode(reader); if (prop != null) { node.Properties.Add(name, prop); } } // 2. Xaml2009 primitives, x:Arguments, ... else if (reader.NamespaceURI == X2009Uri && reader.LocalName == "Arguments") { var prop = ReadNode(reader); if (prop != null) { node.Properties.Add(XmlName.xArguments, prop); } } // 3. DataTemplate (should be handled by 4.) else if ((node.XmlType.NamespaceUri == XFUri || node.XmlType.NamespaceUri == NUI2018Uri) && (node.XmlType.Name == "DataTemplate" || node.XmlType.Name == "ControlTemplate")) { var prop = ReadNode(reader, true); if (prop != null) { node.Properties.Add(XmlName._CreateContent, prop); } } // 4. Implicit content, implicit collection, or collection syntax. Add to CollectionItems, resolve case later. else { var item = ReadNode(reader, true); if (item != null) { node.CollectionItems.Add(item); } } break; case XmlNodeType.Whitespace: break; case XmlNodeType.Text: case XmlNodeType.CDATA: if (node.CollectionItems.Count == 1 && node.CollectionItems[0] is ValueNode) { ((ValueNode)node.CollectionItems[0]).Value += reader.Value.Trim(); } else { node.CollectionItems.Add(new ValueNode(reader.Value.Trim(), (IXmlNamespaceResolver)reader)); } break; default: Debug.WriteLine("Unhandled node {0} {1} {2}", reader.NodeType, reader.Name, reader.Value); break; } } }
public override object ReadObject(XmlReader reader) { ArrayOfstring ArrayOfstringField = null; if (IsParentStartElement(reader, false, true)) { ArrayOfstringField = new ArrayOfstring(); reader.Read(); System.Collections.ArrayList string_List = new System.Collections.ArrayList(); for (int i = 0; (i > -1); i = (i + 1)) { if (!IsChildStartElement(reader, "string", false, false)) { ArrayOfstringField.STRING = new string[string_List.Count]; string_List.CopyTo(ArrayOfstringField.STRING); break; } string_List.Add(ReadString(reader)); } reader.ReadEndElement(); } return ArrayOfstringField; }
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(); }
public StackPanel( CreateParams parentParams, XmlReader reader ) { Initialize( ); // Always get our style first mStyle = parentParams.Style; Styles.Style.ParseStyleAttributesWithDefaults( reader, ref mStyle, ref ControlStyles.mStackPanel ); // check for attributes we support RectangleF bounds = new RectangleF( ); SizeF parentSize = new SizeF( parentParams.Width, parentParams.Height ); ParseCommonAttribs( reader, ref parentSize, ref bounds ); // Get margins and padding RectangleF padding; RectangleF margin; GetMarginsAndPadding( ref mStyle, ref parentSize, ref bounds, out margin, out padding ); // apply margins to as much of the bounds as we can (bottom must be done by our parent container) ApplyImmediateMargins( ref bounds, ref margin, ref parentSize ); Margin = margin; // check for border styling int borderPaddingPx = 0; if ( mStyle.mBorderColor.HasValue ) { BorderView.BorderColor = mStyle.mBorderColor.Value; } if( mStyle.mBorderRadius.HasValue ) { BorderView.CornerRadius = mStyle.mBorderRadius.Value; } if( mStyle.mBorderWidth.HasValue ) { BorderView.BorderWidth = mStyle.mBorderWidth.Value; borderPaddingPx = (int)Rock.Mobile.Graphics.Util.UnitToPx( mStyle.mBorderWidth.Value + PrivateNoteConfig.BorderPadding ); } if( mStyle.mBackgroundColor.HasValue ) { BorderView.BackgroundColor = mStyle.mBackgroundColor.Value; } // // now calculate the available width based on padding. (Don't actually change our width) float availableWidth = bounds.Width - padding.Left - padding.Width - (borderPaddingPx * 2); // now read what our children's alignment should be // check for alignment string result = reader.GetAttribute( "ChildAlignment" ); if( string.IsNullOrEmpty( result ) == false ) { switch( result ) { case "Left": { ChildHorzAlignment = Alignment.Left; break; } case "Right": { ChildHorzAlignment = Alignment.Right; break; } case "Center": { ChildHorzAlignment = Alignment.Center; break; } default: { ChildHorzAlignment = mStyle.mAlignment.Value; break; } } } else { // if it wasn't specified, use left alignment. ChildHorzAlignment = Alignment.Left; } // Parse Child Controls bool finishedParsing = false; while( finishedParsing == false && reader.Read( ) ) { switch( reader.NodeType ) { case XmlNodeType.Element: { // let each child have our available width. Style style = new Style( ); style = mStyle; style.mAlignment = ChildHorzAlignment; IUIControl control = Parser.TryParseControl( new CreateParams( this, availableWidth, parentParams.Height, ref style ), reader ); if( control != null ) { ChildControls.Add( control ); } break; } case XmlNodeType.EndElement: { // if we hit the end of our label, we're done. //if( reader.Name == "StackPanel" || reader.Name == "SP" ) if( ElementTagMatches( reader.Name ) ) { finishedParsing = true; } break; } } } LayoutStackPanel( bounds, padding.Left, padding.Top, availableWidth, padding.Height, borderPaddingPx ); }
public void ParseContextSetupReply(XmlReader reader) { // verify node is "context_setup_reply if (reader.Name == "context_setup_reply") { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "apiversion") { csr.apiversion = reader.ReadElementContentAsString(); //UnityEngine.Debug.Log("apiversion=" + csr.apiversion); } if (reader.NodeType == XmlNodeType.Element && reader.Name == "setup_request_status") { csr.setup_request_status = reader.ReadElementContentAsInt(); //UnityEngine.Debug.Log("setup_request_status=" + csr.setup_request_status); } if (reader.NodeType == XmlNodeType.Element && reader.Name == "context_uid") { csr.context_uid = reader.ReadElementContentAsString(); #if SHOW_INIT QuickInfoMsg msg = new QuickInfoMsg(); msg.title = "NLU STATUS"; msg.text = "NLU Initialized : " + CmdTime + " seconds"; msg.timeout = 2.0f; QuickInfoDialog.GetInstance().PutMessage(msg); #endif Initialized = true; //UnityEngine.Debug.Log("context_uid=" + csr.context_uid); } } } }
/// <summary> /// Reads the elements from the loaded xmldocument in LoadResources /// </summary> /// <param name='reader'> /// Reader. /// </param> private void ReadElements(XmlReader reader) { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: //If this is a chunk of data, then parse it if (reader.Name == "data") { ReadData(reader); } break; } } }
/// <summary> /// Parse a Logiqx XML DAT and return all found games and roms within /// </summary> /// <param name="filename">Name of the file to be parsed</param> /// <param name="sysid">System ID for the DAT</param> /// <param name="srcid">Source ID for the DAT</param> /// <param name="keep">True if full pathnames are to be kept, false otherwise (default)</param> /// <param name="clean">True if game names are sanitized, false otherwise (default)</param> /// <param name="remUnicode">True if we should remove non-ASCII characters from output, false otherwise (default)</param> public override void ParseFile( // Standard Dat parsing string filename, int sysid, int srcid, // Miscellaneous bool keep, bool clean, bool remUnicode) { // Prepare all internal variables Encoding enc = Utilities.GetEncoding(filename); XmlReader xtr = Utilities.GetXmlTextReader(filename); List <string> dirs = new List <string>(); // If we got a null reader, just return if (xtr == null) { return; } // Otherwise, read the file to the end try { xtr.MoveToContent(); while (!xtr.EOF) { // We only want elements if (xtr.NodeType != XmlNodeType.Element) { // If we're ending a dir, remove the last item from the dirs list, if possible if (xtr.Name == "dir" && dirs.Count > 0) { dirs.RemoveAt(dirs.Count - 1); } xtr.Read(); continue; } switch (xtr.Name) { // The datafile tag can have some attributes case "datafile": // string build = xtr.GetAttribute("build"); // string debug = xtr.GetAttribute("debug"); // (yes|no) "no" xtr.Read(); break; // We want to process the entire subtree of the header case "header": ReadHeader(xtr.ReadSubtree(), keep); // Skip the header node now that we've processed it xtr.Skip(); break; // Unique to RomVault-created DATs case "dir": Type = "SuperDAT"; dirs.Add(xtr.GetAttribute("name") ?? ""); xtr.Read(); break; // We want to process the entire subtree of the game case "machine": // New-style Logiqx case "game": // Old-style Logiqx ReadMachine(xtr.ReadSubtree(), dirs, filename, sysid, srcid, keep, clean, remUnicode); // Skip the machine now that we've processed it xtr.Skip(); break; default: xtr.Read(); break; } } } catch (Exception ex) { Globals.Logger.Warning("Exception found while parsing '{0}': {1}", filename, ex); // For XML errors, just skip the affected node xtr?.Read(); } xtr.Dispose(); }
internal XComment(XmlReader r) { value = r.Value; r.Read(); }
public static Result ImportXml(XmlReader xr, out string id, IWarningLogger log) { id = null; if (xr.Name != "result") { log.Warning(3019, "Expected 'result' node but got " + xr.Name + " on XML import", null); return(null); } id = xr.GetAttribute("id"); if (id == null) { log.Warning(3019, "No 'id' attribute on result element during XML import", null); return(null); } log.PushLocation(id); string type = xr.GetAttribute("type"); if (type == null) { log.Warning(3019, "No 'type' attribute on result element during XML import", null); log.PopLocation(); return(null); } int depth = xr.Depth; Result r; while (xr.Read()) { if (xr.NodeType != XmlNodeType.Attribute && xr.NodeType != XmlNodeType.Whitespace) { break; } } //Console.WriteLine ("here: id {0}, type {1}", id, type); //Console.WriteLine ("here: {0}: {1} = \"{2}\"; ac = {3}, d = {4} (vs {5})", xr.NodeType, xr.Name, xr.Value, // xr.AttributeCount, xr.Depth, depth); try { Type t; t = System.Type.GetType(type, false); if (t == null) { log.Warning(3019, "Unknown result type during XML import", type); log.PopLocation(); return(null); } if (!t.IsSubclassOf(typeof(Result))) { log.Warning(3019, "Type is not a subclass of Result", t.FullName); log.PopLocation(); return(null); } r = MyCreateInstance(t); if (r.ImportXml(xr, log)) { log.PopLocation(); // error will be reported return(null); } log.PopLocation(); } finally { while (xr.Depth > depth) { if (!xr.Read()) { log.Warning(3019, "Unexpected end of XML document", null); break; } } } return(r); }
public void ParseUtteranceReply(XmlReader reader) { pur = new process_utterance_reply(); // verify node is "context_setup_reply if (reader.Name == "process_utterance_reply") { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "utterance_request_status") { pur.utterance_request_status = reader.ReadElementContentAsInt(); #if DEBUG_REPLY UnityEngine.Debug.Log("utterance status=" + pur.utterance_request_status); #endif // report error if (pur.utterance_request_status < 0 && errorCallback != null) { //'utterance_request_status' indicates if utterance process is final or NLU server starts // 0: OK. the 'match_record' list contains the simulation command(s) for the utterance // 1: NLU server executes 'clarifying NLU sub-session' (see "SiTEL-SMS API Reqs & Specs" document) //-1: cannot process utterance //-2: MLU not ready for utterance processing //-3: missing utterance text string error="none"; switch (pur.utterance_request_status) { case -1: error = "error -1: cannot process utterance"; break; case -2: error = "error -2: MLU not ready for utterance processing"; break; case -3: error = "error -3: missing utterance text"; break; } errorCallback(error); } } if (reader.NodeType == XmlNodeType.Element && reader.Name == "match_records") { List<sim_command_param> parameters=null; List<missing_sim_command_param> missing = null; match_record record = null; while (reader.Read()) { #if DEBUG_REPLY if (reader.NodeType == XmlNodeType.Element) UnityEngine.Debug.Log("NODE_NAME=" + reader.Name + ", NODE_TYPE=" + reader.NodeType.ToString()); else if (reader.NodeType == XmlNodeType.EndElement) UnityEngine.Debug.Log("NODE_END=" + reader.Name + ", NODE_TYPE=" + reader.NodeType.ToString()); else UnityEngine.Debug.Log("NODE_TYPE=" + reader.NodeType.ToString()); #endif // match START element if (reader.NodeType == XmlNodeType.Element && reader.Name == "match") { if (reader.IsEmptyElement == false) { record = new match_record(); if ( reader.MoveToAttribute("index") == false ) UnityEngine.Debug.Log("CAN'T FIND INDEX!"); record.index = reader.ReadContentAsInt(); if ( reader.MoveToAttribute("sim_command") == false ) UnityEngine.Debug.Log("CAN'T FIND SIM_COMMAND!"); record.sim_command = reader.ReadContentAsString(); if ( reader.MoveToAttribute("score") == false ) UnityEngine.Debug.Log("CAN'T FIND SCORE!"); record.score = reader.ReadContentAsFloat(); if ( reader.MoveToAttribute("input") == false ) UnityEngine.Debug.Log("CAN'T FIND INPUT!"); record.input = reader.ReadContentAsString(); #if DEBUG_REPLY UnityEngine.Debug.Log("START MATCH : sim_command=" + record.sim_command); #endif } } // match END element if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "match") { if (reader.IsEmptyElement == false) { #if DEBUG_REPLY UnityEngine.Debug.Log("END MATCH"); #endif pur.match_records.Add(record); // do callback here, we have a valid match!! if (utteranceCallback != null) utteranceCallback(record); record.Debug(); } } // sim command parameters if (reader.NodeType == XmlNodeType.Element && reader.Name == "sim_command_params") { record.parameters = new List<sim_command_param>(); if (reader.IsEmptyElement == false) { #if DEBUG_REPLY UnityEngine.Debug.Log("SIM_COMMAND_PARAMS"); #endif } } // sc_param if (reader.NodeType == XmlNodeType.Element && reader.Name == "sc_param") { sim_command_param sc_param = new sim_command_param(); if (reader.IsEmptyElement == false) { if (reader.MoveToAttribute("mandatory") == false) UnityEngine.Debug.Log("CAN'T FIND MANDATORY!"); sc_param.mandatory = reader.ReadContentAsString(); if ( reader.MoveToAttribute("name") == false ) UnityEngine.Debug.Log("CAN'T FIND NAME!"); sc_param.name = reader.ReadContentAsString(); // value reader.Read(); sc_param.value = reader.Value.Trim(); // add it record.parameters.Add(sc_param); sc_param.Debug(); } } if (reader.NodeType == XmlNodeType.Element && reader.Name == "missing_sim_command_params") { record.missing_parameters = new List<missing_sim_command_param>(); if (reader.IsEmptyElement == false) { #if DEBUG_REPLY UnityEngine.Debug.Log("MISSING_SIM_COMMAND_PARAMS"); #endif } } if (reader.NodeType == XmlNodeType.Element && reader.Name == "missing_sc_param") { if (reader.IsEmptyElement == false) { missing_sim_command_param sc_param = new missing_sim_command_param(); #if DEBUG_REPLY if (reader.MoveToAttribute("mandatory") == false) UnityEngine.Debug.Log("MISSING CAN'T FIND MANDATORY!"); sc_param.mandatory = reader.ReadContentAsString(); if (reader.MoveToAttribute("name") == false) UnityEngine.Debug.Log("MISSING CAN'T FIND NAME!"); #endif sc_param.name = reader.ReadContentAsString(); record.missing_parameters.Add(sc_param); sc_param.Debug(); } } if (reader.NodeType == XmlNodeType.Element && reader.Name == "readback") { if (reader.IsEmptyElement == false) { reader.Read(); record.readback = reader.Value.Trim(); #if DEBUG_REPLY UnityEngine.Debug.Log("READBACK=<" + record.readback + ">"); #endif } } if (reader.NodeType == XmlNodeType.Element && reader.Name == "feedback") { if (reader.IsEmptyElement == false) { reader.Read(); record.feedback = reader.Value.Trim(); #if DEBUG_REPLY UnityEngine.Debug.Log("FEEDBACK=<" + record.feedback + ">"); #endif } } if (reader.NodeType == XmlNodeType.Element && reader.Name == "command_subject") { if (reader.IsEmptyElement == false) { reader.Read(); record.command_subject = reader.Value.Trim(); #if DEBUG_REPLY UnityEngine.Debug.Log("SUBJECT=<" + record.command_subject + ">"); #endif } } } } } } }
private void Bar(XmlReader reader) { reader.Read(); string foo = reader.ReadOuterXml(); CError.Compare(foo, "<device xmlns=\"http://www.test.com/\"> <thing>1</thing> </device>", "<device xmlns=\"http://www.test.com/\"><thing>1</thing></device>", "mismatch"); }
/// <summary> /// Parse an OfflineList XML DAT and return all found games and roms within /// </summary> /// <param name="filename">Name of the file to be parsed</param> /// <param name="sysid">System ID for the DAT</param> /// <param name="srcid">Source ID for the DAT</param> /// <param name="keep">True if full pathnames are to be kept, false otherwise (default)</param> /// <param name="clean">True if game names are sanitized, false otherwise (default)</param> /// <param name="remUnicode">True if we should remove non-ASCII characters from output, false otherwise (default)</param> /// <remarks> /// </remarks> public override void ParseFile( // Standard Dat parsing string filename, int sysid, int srcid, // Miscellaneous bool keep, bool clean, bool remUnicode) { Encoding enc = Utilities.GetEncoding(filename); XmlReader xtr = Utilities.GetXmlTextReader(filename); // If we got a null reader, just return if (xtr == null) { return; } // Otherwise, read the file to the end try { xtr.MoveToContent(); while (!xtr.EOF) { // We only want elements if (xtr.NodeType != XmlNodeType.Element) { xtr.Read(); continue; } switch (xtr.Name) { case "configuration": ReadConfiguration(xtr.ReadSubtree(), keep); // Skip the configuration node now that we've processed it xtr.Skip(); break; case "games": ReadGames(xtr.ReadSubtree(), keep, clean, remUnicode); // Skip the games node now that we've processed it xtr.Skip(); break; default: xtr.Read(); break; } } } catch (Exception ex) { Globals.Logger.Warning("Exception found while parsing '{0}': {1}", filename, ex); // For XML errors, just skip the affected node xtr?.Read(); } xtr.Dispose(); }
internal XProcessingInstruction(XmlReader r) { target = r.Name; data = r.Value; r.Read(); }
private void Foo(XmlReader reader) { reader.Read(); Bar(reader.ReadSubtree()); }
public static void ParseListAllMyBucketsResult(Stream inStream, ListAllMyBuckets result) { XmlReader xmlReader = XmlReader.Create(inStream); ListAllMyBuckets.Bucket bucket = null; while (xmlReader.Read()) { switch (xmlReader.NodeType) { case XmlNodeType.Element: // element start if ("Owner".Equals(xmlReader.Name, StringComparison.OrdinalIgnoreCase)) // get element name { result.owner = new ListAllMyBuckets.Owner(); } else if ("ID".Equals(xmlReader.Name, StringComparison.OrdinalIgnoreCase)) { xmlReader.Read(); result.owner.id = xmlReader.Value; // get element value } else if ("DisplayName".Equals(xmlReader.Name, StringComparison.OrdinalIgnoreCase)) { xmlReader.Read(); result.owner.disPlayName = xmlReader.Value; } else if ("Buckets".Equals(xmlReader.Name, StringComparison.OrdinalIgnoreCase)) { result.buckets = new List <ListAllMyBuckets.Bucket>(); } else if ("Bucket".Equals(xmlReader.Name, StringComparison.OrdinalIgnoreCase)) { bucket = new ListAllMyBuckets.Bucket(); } else if ("Bucket".Equals(xmlReader.Name, StringComparison.OrdinalIgnoreCase)) { bucket = new ListAllMyBuckets.Bucket(); } else if ("Name".Equals(xmlReader.Name, StringComparison.OrdinalIgnoreCase)) { xmlReader.Read(); bucket.name = xmlReader.Value; } else if ("Location".Equals(xmlReader.Name, StringComparison.OrdinalIgnoreCase)) { xmlReader.Read(); bucket.location = xmlReader.Value; } else if ("CreateDate".Equals(xmlReader.Name, StringComparison.OrdinalIgnoreCase)) { xmlReader.Read(); bucket.createDate = xmlReader.Value; } break; case XmlNodeType.EndElement: //end element if ("Bucket".Equals(xmlReader.Name, StringComparison.OrdinalIgnoreCase)) { result.buckets.Add(bucket); bucket = null; } break; } } }
static void AddElementToList(string in_currentPathInProj, XmlReader in_reader, AssetType in_type, LinkedList<AkWwiseProjectData.PathElement> in_pathAndIcons, int in_wwuIndex) { if (in_type.RootDirectoryName == "Events" || in_type.RootDirectoryName == "Master-Mixer Hierarchy" || in_type.RootDirectoryName == "SoundBanks") { AkWwiseProjectData.Event valueToAdd = new AkWwiseProjectData.Event(); valueToAdd.Name = in_reader.GetAttribute("Name"); valueToAdd.Guid = new Guid(in_reader.GetAttribute("ID")).ToByteArray(); valueToAdd.ID = (int)AkUtilities.ShortIDGenerator.Compute(valueToAdd.Name); valueToAdd.Path = in_type.RootDirectoryName == "Master-Mixer Hierarchy" ? in_currentPathInProj : Path.Combine(in_currentPathInProj, valueToAdd.Name); valueToAdd.PathAndIcons = new List<AkWwiseProjectData.PathElement>(in_pathAndIcons); if (in_type.RootDirectoryName == "Events") { valueToAdd.PathAndIcons.Add(new AkWwiseProjectData.PathElement(valueToAdd.Name, AkWwiseProjectData.WwiseObjectType.EVENT)); AkWwiseProjectInfo.GetData().EventWwu[in_wwuIndex].List.Add(valueToAdd); } else if (in_type.RootDirectoryName == "SoundBanks") { valueToAdd.PathAndIcons.Add(new AkWwiseProjectData.PathElement(valueToAdd.Name, AkWwiseProjectData.WwiseObjectType.SOUNDBANK)); AkWwiseProjectInfo.GetData().BankWwu[in_wwuIndex].List.Add(valueToAdd); } else { AkWwiseProjectInfo.GetData().AuxBusWwu[in_wwuIndex].List.Add(valueToAdd); } in_reader.Read(); } else if (in_type.RootDirectoryName == "States" || in_type.RootDirectoryName == "Switches") { var XmlElement = XNode.ReadFrom(in_reader) as XElement; AkWwiseProjectData.GroupValue valueToAdd = new AkWwiseProjectData.GroupValue(); AkWwiseProjectData.WwiseObjectType SubElemIcon; valueToAdd.Name = XmlElement.Attribute("Name").Value; valueToAdd.Guid = new Guid(XmlElement.Attribute("ID").Value).ToByteArray(); valueToAdd.ID = (int)AkUtilities.ShortIDGenerator.Compute(valueToAdd.Name); valueToAdd.Path = Path.Combine(in_currentPathInProj, valueToAdd.Name); valueToAdd.PathAndIcons = new List<AkWwiseProjectData.PathElement>(in_pathAndIcons); if (in_type.RootDirectoryName == "States") { SubElemIcon = AkWwiseProjectData.WwiseObjectType.STATE; valueToAdd.PathAndIcons.Add(new AkWwiseProjectData.PathElement(valueToAdd.Name, AkWwiseProjectData.WwiseObjectType.STATEGROUP)); } else { SubElemIcon = AkWwiseProjectData.WwiseObjectType.SWITCH; valueToAdd.PathAndIcons.Add(new AkWwiseProjectData.PathElement(valueToAdd.Name, AkWwiseProjectData.WwiseObjectType.SWITCHGROUP)); } XName ChildrenList = XName.Get("ChildrenList"); XName ChildElem = XName.Get(in_type.ChildElementName); XElement ChildrenElement = XmlElement.Element(ChildrenList); if (ChildrenElement != null) { foreach (var element in ChildrenElement.Elements(ChildElem)) { if (element.Name == in_type.ChildElementName) { string elementName = element.Attribute("Name").Value; valueToAdd.values.Add(elementName); valueToAdd.ValueGuids.Add(new AkWwiseProjectData.ByteArrayWrapper( new Guid(element.Attribute("ID").Value).ToByteArray())); valueToAdd.valueIDs.Add((int)AkUtilities.ShortIDGenerator.Compute(elementName)); valueToAdd.ValueIcons.Add(new AkWwiseProjectData.PathElement(elementName, SubElemIcon)); } } } if (in_type.RootDirectoryName == "States") { AkWwiseProjectInfo.GetData().StateWwu[in_wwuIndex].List.Add(valueToAdd); } else { AkWwiseProjectInfo.GetData().SwitchWwu[in_wwuIndex].List.Add(valueToAdd); } } else { Debug.LogError("WwiseUnity: Unknown asset type in WWU parser"); } }
/// <summary> /// Parse a MAME XML DAT and return all found games and roms within /// </summary> /// <param name="filename">Name of the file to be parsed</param> /// <param name="sysid">System ID for the DAT</param> /// <param name="srcid">Source ID for the DAT</param> /// <param name="keep">True if full pathnames are to be kept, false otherwise (default)</param> /// <param name="clean">True if game names are sanitized, false otherwise (default)</param> /// <param name="remUnicode">True if we should remove non-ASCII characters from output, false otherwise (default)</param> /// <remarks> /// </remarks> public override void ParseFile( // Standard Dat parsing string filename, int sysid, int srcid, // Miscellaneous bool keep, bool clean, bool remUnicode) { // Prepare all internal variables Encoding enc = Utilities.GetEncoding(filename); XmlReader xtr = Utilities.GetXmlTextReader(filename); // If we got a null reader, just return if (xtr == null) { return; } // Otherwise, read the file to the end try { xtr.MoveToContent(); while (!xtr.EOF) { // We only want elements if (xtr.NodeType != XmlNodeType.Element) { xtr.Read(); continue; } switch (xtr.Name) { case "mame": Name = (String.IsNullOrWhiteSpace(Name) ? xtr.GetAttribute("build") : Name); Description = (String.IsNullOrWhiteSpace(Description) ? Name : Name); // string mame_debug = xtr.GetAttribute("debug"); // (yes|no) "no" // string mame_mameconfig = xtr.GetAttribute("mameconfig"); CDATA xtr.Read(); break; // Handle M1 DATs since they're 99% the same as a SL DAT case "m1": Name = (String.IsNullOrWhiteSpace(Name) ? "M1" : Name); Description = (String.IsNullOrWhiteSpace(Description) ? "M1" : Description); Version = (String.IsNullOrWhiteSpace(Version) ? xtr.GetAttribute("version") ?? "" : Version); xtr.Read(); break; // We want to process the entire subtree of the machine case "game": // Some older DATs still use "game" case "machine": ReadMachine(xtr.ReadSubtree(), filename, sysid, srcid, keep, clean, remUnicode); // Skip the machine now that we've processed it xtr.Skip(); break; default: xtr.Read(); break; } } } catch (Exception ex) { Globals.Logger.Warning("Exception found while parsing '{0}': {1}", filename, ex); // For XML errors, just skip the affected node xtr?.Read(); } xtr.Dispose(); }
private void ComputeFieldInfo(DynamicTraceEventData template, XmlReader reader) { List<string> payloadNames = new List<string>(); List<DynamicTraceEventData.PayloadFetch> payloadFetches = new List<DynamicTraceEventData.PayloadFetch>(); short offset = 0; while (reader.Read()) { if (reader.Name == "data") { Type type = GetTypeForManifestTypeName(reader.GetAttribute("inType")); short size = DynamicTraceEventData.SizeOfType(type); // TODO There is disagreement in what win:Boolean means. Currently it is serialized as 1 byte // by manage code. However all other windows tools assume it is 4 bytes. we are likely // to change this to align with windows at some point. payloadNames.Add(reader.GetAttribute("name")); payloadFetches.Add(new DynamicTraceEventData.PayloadFetch(offset, size, type)); if (offset >= 0) { Debug.Assert(size != 0); if (size >= 0) offset += size; else offset = short.MinValue; } } } template.payloadNames = payloadNames.ToArray(); template.payloadFetches = payloadFetches.ToArray(); }
/// <summary> /// Parse an SabreDat XML DAT and return all found directories and files within /// </summary> /// <param name="filename">Name of the file to be parsed</param> /// <param name="sysid">System ID for the DAT</param> /// <param name="srcid">Source ID for the DAT</param> /// <param name="keep">True if full pathnames are to be kept, false otherwise (default)</param> /// <param name="clean">True if game names are sanitized, false otherwise (default)</param> /// <param name="remUnicode">True if we should remove non-ASCII characters from output, false otherwise (default)</param> public override void ParseFile( // Standard Dat parsing string filename, int sysid, int srcid, // Miscellaneous bool keep, bool clean, bool remUnicode) { // Prepare all internal variables bool empty = true; string key = ""; List <string> parent = new List <string>(); Encoding enc = Utilities.GetEncoding(filename); XmlReader xtr = Utilities.GetXmlTextReader(filename); // If we got a null reader, just return if (xtr == null) { return; } // Otherwise, read the file to the end try { xtr.MoveToContent(); while (!xtr.EOF) { // If we're ending a folder or game, take care of possibly empty games and removing from the parent if (xtr.NodeType == XmlNodeType.EndElement && (xtr.Name == "directory" || xtr.Name == "dir")) { // If we didn't find any items in the folder, make sure to add the blank rom if (empty) { string tempgame = String.Join("\\", parent); Rom rom = new Rom("null", tempgame, omitFromScan: Hash.DeepHashes); // TODO: All instances of Hash.DeepHashes should be made into 0x0 eventually // Now process and add the rom key = ParseAddHelper(rom, clean, remUnicode); } // Regardless, end the current folder int parentcount = parent.Count; if (parentcount == 0) { Globals.Logger.Verbose("Empty parent '{0}' found in '{1}'", String.Join("\\", parent), filename); empty = true; } // If we have an end folder element, remove one item from the parent, if possible if (parentcount > 0) { parent.RemoveAt(parent.Count - 1); if (keep && parentcount > 1) { Type = (String.IsNullOrWhiteSpace(Type) ? "SuperDAT" : Type); } } } // We only want elements if (xtr.NodeType != XmlNodeType.Element) { xtr.Read(); continue; } switch (xtr.Name) { // We want to process the entire subtree of the header case "header": ReadHeader(xtr.ReadSubtree(), keep); // Skip the header node now that we've processed it xtr.Skip(); break; case "dir": case "directory": empty = ReadDirectory(xtr.ReadSubtree(), parent, filename, sysid, srcid, keep, clean, remUnicode); // Skip the directory node now that we've processed it xtr.Read(); break; default: xtr.Read(); break; } } } catch (Exception ex) { Globals.Logger.Warning("Exception found while parsing '{0}': {1}", filename, ex); // For XML errors, just skip the affected node xtr?.Read(); } xtr.Dispose(); }
private static void readWaySubtree(XmlReader subtree, List<OsmNodeReference> references, List<OsmTag> tags) { while (subtree.Read ()) { switch (subtree.Name) { case "tag": tags.Add (new OsmTag (subtree ["k"], subtree ["v"])); break; case "nd": references.Add (new OsmNodeReference (long.Parse (subtree ["ref"]))); break; } } }
internal void ReadContentFrom(XmlReader r, LoadOptions o) { if ((o & (LoadOptions.SetBaseUri | LoadOptions.SetLineInfo)) == 0) { ReadContentFrom(r); return; } if (r.ReadState != ReadState.Interactive) throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive); XContainer c = this; XNode n = null; NamespaceCache eCache = new NamespaceCache(); NamespaceCache aCache = new NamespaceCache(); string baseUri = (o & LoadOptions.SetBaseUri) != 0 ? r.BaseURI : null; IXmlLineInfo li = (o & LoadOptions.SetLineInfo) != 0 ? r as IXmlLineInfo : null; do { string uri = r.BaseURI; switch (r.NodeType) { case XmlNodeType.Element: { XElement e = new XElement(eCache.Get(r.NamespaceURI).GetName(r.LocalName)); if (baseUri != null && baseUri != uri) { e.SetBaseUri(uri); } if (li != null && li.HasLineInfo()) { e.SetLineInfo(li.LineNumber, li.LinePosition); } if (r.MoveToFirstAttribute()) { do { XAttribute a = new XAttribute(aCache.Get(r.Prefix.Length == 0 ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value); if (li != null && li.HasLineInfo()) { a.SetLineInfo(li.LineNumber, li.LinePosition); } e.AppendAttributeSkipNotify(a); } while (r.MoveToNextAttribute()); r.MoveToElement(); } c.AddNodeSkipNotify(e); if (!r.IsEmptyElement) { c = e; if (baseUri != null) { baseUri = uri; } } break; } case XmlNodeType.EndElement: { if (c.content == null) { c.content = string.Empty; } // Store the line info of the end element tag. // Note that since we've got EndElement the current container must be an XElement XElement e = c as XElement; Debug.Assert(e != null, "EndElement received but the current container is not an element."); if (e != null && li != null && li.HasLineInfo()) { e.SetEndElementLineInfo(li.LineNumber, li.LinePosition); } if (c == this) return; if (baseUri != null && c.HasBaseUri) { baseUri = c.parent.BaseUri; } c = c.parent; break; } case XmlNodeType.Text: case XmlNodeType.SignificantWhitespace: case XmlNodeType.Whitespace: if ((baseUri != null && baseUri != uri) || (li != null && li.HasLineInfo())) { n = new XText(r.Value); } else { c.AddStringSkipNotify(r.Value); } break; case XmlNodeType.CDATA: n = new XCData(r.Value); break; case XmlNodeType.Comment: n = new XComment(r.Value); break; case XmlNodeType.ProcessingInstruction: n = new XProcessingInstruction(r.Name, r.Value); break; case XmlNodeType.DocumentType: n = new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value); break; case XmlNodeType.EntityReference: if (!r.CanResolveEntity) throw new InvalidOperationException(SR.InvalidOperation_UnresolvedEntityReference); r.ResolveEntity(); break; case XmlNodeType.EndEntity: break; default: throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, r.NodeType)); } if (n != null) { if (baseUri != null && baseUri != uri) { n.SetBaseUri(uri); } if (li != null && li.HasLineInfo()) { n.SetLineInfo(li.LineNumber, li.LinePosition); } c.AddNodeSkipNotify(n); n = null; } } while (r.Read()); }
private static void readNodeSubtree(XmlReader subtree, List<OsmTag> tags) { while (subtree.Read ()) { switch (subtree.Name) { case "tag": tags.Add (new OsmTag (subtree ["k"], subtree ["v"])); break; } } }
public void ReadXmlPrototype(XmlReader reader_parent) { Name = reader_parent.GetAttribute("Name"); Goals = new List <QuestGoal>(); Rewards = new List <QuestReward>(); PreRequiredCompletedQuest = new List <string>(); XmlReader reader = reader_parent.ReadSubtree(); while (reader.Read()) { switch (reader.Name) { case "Description": reader.Read(); Description = reader.ReadContentAsString(); break; case "PreRequiredCompletedQuests": XmlReader subReader = reader.ReadSubtree(); while (subReader.Read()) { if (subReader.Name == "PreRequiredCompletedQuest") { PreRequiredCompletedQuest.Add(subReader.GetAttribute("Name")); } } break; case "Goals": XmlReader goals_reader = reader.ReadSubtree(); while (goals_reader.Read()) { if (goals_reader.Name == "Goal") { QuestGoal goal = new QuestGoal(); goal.ReadXmlPrototype(goals_reader); Goals.Add(goal); } } break; case "Rewards": XmlReader reward_reader = reader.ReadSubtree(); while (reward_reader.Read()) { if (reward_reader.Name == "Reward") { QuestReward reward = new QuestReward(); reward.ReadXmlPrototype(reward_reader); Rewards.Add(reward); } } break; } } }