public void LoadTripData(string folderPath) { // save the base folder path dataPath = folderPath; // generate path to the trips.dat XML, and then load it string metadataPath = folderPath + "\\trips.dat"; XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(metadataPath); // grab ride list via the XML root node in trips.dat XmlNodeList xmlNodes = xmlDocument.GetElementsByTagName("TripDetailsItem"); foreach (XmlNode node in xmlNodes) {// loop through the ride list and store the metadata into the variables XmlNodeReader xmlNodeReader = new XmlNodeReader(node); // for some reason, need to "read" twice to access the data xmlNodeReader.Read(); xmlNodeReader.Read(); FileName.Add(xmlNodeReader.ReadElementContentAsString()); Title.Add(xmlNodeReader.ReadElementContentAsString()); Distance.Add(xmlNodeReader.ReadElementContentAsDouble()); // the duration is stored as ticks; cast as DateTime // for conversion to seconds later duration.Add(new DateTime(xmlNodeReader.ReadElementContentAsLong())); DateOfRoute.Add(xmlNodeReader.ReadElementContentAsDateTime()); CaloriesBurned.Add(xmlNodeReader.ReadElementContentAsInt()); Weather.Add(xmlNodeReader.ReadElementContentAsInt()); CourseJoy.Add(xmlNodeReader.ReadElementContentAsInt()); ExtraNotes.Add(xmlNodeReader.ReadElementContentAsString()); } }
internal static void ImportPolicy(MetadataImporter importer, PolicyConversionContext policyContext) { XmlElement assertion = PolicyConversionContext.FindAssertion(policyContext.GetBindingAssertions(), TransportPolicyConstants.WindowsTransportSecurityName, TransportPolicyConstants.DotNetFramingNamespace, true); if (assertion != null) { WindowsStreamSecurityBindingElement windowsBindingElement = new WindowsStreamSecurityBindingElement(); XmlReader reader = new XmlNodeReader(assertion); reader.ReadStartElement(); string protectionLevelString = null; if (reader.IsStartElement( TransportPolicyConstants.ProtectionLevelName, TransportPolicyConstants.DotNetFramingNamespace) && !reader.IsEmptyElement) { protectionLevelString = reader.ReadElementContentAsString(); } if (string.IsNullOrEmpty(protectionLevelString)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException( SR.GetString(SR.ExpectedElementMissing, TransportPolicyConstants.ProtectionLevelName, TransportPolicyConstants.DotNetFramingNamespace))); } windowsBindingElement.ProtectionLevel = (ProtectionLevel)Enum.Parse(typeof(ProtectionLevel), protectionLevelString); policyContext.BindingElements.Add(windowsBindingElement); } }
private List <List <(string, string)> > ParserInternal(string data) { var items = new List <List <(string, string)> >(); var doc = new XmlDocument(); doc.LoadXml(data); doc.IterateThroughAllNodes( node => { var inner = new List <(string, string)>(); var xr = new XmlNodeReader(node); while (xr.Read()) { while (xr.Read()) { while (xr.IsStartElement()) { inner.Add((xr.Name, xr.ReadElementContentAsString())); } } } items.Add(inner); }); return(items); }
internal static string ReadTextElementAsTrimmedString(XmlElement element) { if (element == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("element"); } XmlReader reader = new XmlNodeReader(element); reader.MoveToContent(); return(XmlUtil.Trim(reader.ReadElementContentAsString())); }
static Book XmlReadNext(XmlNodeReader xmlNodeReader) { Book newBook = new Book(); string author = xmlNodeReader.ReadElementContentAsString(); string title = xmlNodeReader.ReadElementContentAsString(); string genre = xmlNodeReader.ReadElementContentAsString(); string price = xmlNodeReader.ReadElementContentAsString(); string publishDate = xmlNodeReader.ReadElementContentAsString(); string description = xmlNodeReader.ReadElementContentAsString(); DateTime date; DateTime.TryParseExact(publishDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date); decimal p; Decimal.TryParse(price, out p); newBook.Author = author; newBook.Title = title; newBook.Genre = genre; newBook.Price = p; newBook.PublishDate = date; newBook.Description = description; return newBook; }
private string SendCommand(string message) { try { if (oNativeModeClient.Connected) { if (message != null && message.Length > 0) { string response = oNativeModeClient.SendCommand(message.Trim()); } } XmlNodeReader nrdr = oNativeModeClient.LastResponseReader; if (nrdr != null && nrdr.ReadToFollowing("Status")) { if (nrdr.ReadElementContentAsString().Equals("1")) { return(nrdr.ReadElementContentAsString()); } } else { return("未连接"); } } catch (Cognex.InSight.NativeMode.CvsNativeModeResponseException resEx) { return("输入参数无效"); } catch (Cognex.InSight.NativeMode.CvsNativeModeTimeoutException timEx) { return("超时"); } catch (CvsNetworkException notConnected) { return("未连接"); } return("未找到"); }
internal static void ImportPolicy(MetadataImporter importer, PolicyConversionContext policyContext) { XmlElement node = PolicyConversionContext.FindAssertion(policyContext.GetBindingAssertions(), "WindowsTransportSecurity", "http://schemas.microsoft.com/ws/2006/05/framing/policy", true); if (node != null) { WindowsStreamSecurityBindingElement item = new WindowsStreamSecurityBindingElement(); XmlReader reader = new XmlNodeReader(node); reader.ReadStartElement(); string str = null; if (reader.IsStartElement("ProtectionLevel", "http://schemas.microsoft.com/ws/2006/05/framing/policy") && !reader.IsEmptyElement) { str = reader.ReadElementContentAsString(); } if (string.IsNullOrEmpty(str)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.ServiceModel.SR.GetString("ExpectedElementMissing", new object[] { "ProtectionLevel", "http://schemas.microsoft.com/ws/2006/05/framing/policy" }))); } item.ProtectionLevel = (System.Net.Security.ProtectionLevel)Enum.Parse(typeof(System.Net.Security.ProtectionLevel), str); policyContext.BindingElements.Add(item); } }
public void GetAllBooks() { XmlNodeList xmlNodes = _data.GetElementsByTagName("book"); foreach (XmlNode node in xmlNodes) { Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("Selected book id: '{0}', details:", node.Attributes?["id"].Value); Console.ResetColor(); XmlNodeReader xmlNodeReader = new XmlNodeReader(node); xmlNodeReader.Read(); xmlNodeReader.Read(); string author = xmlNodeReader.ReadElementContentAsString(); string title = xmlNodeReader.ReadElementContentAsString(); string genre = xmlNodeReader.ReadElementContentAsString(); string price = xmlNodeReader.ReadElementContentAsString(); string publishDate = xmlNodeReader.ReadElementContentAsString(); string description = xmlNodeReader.ReadElementContentAsString(); Console.WriteLine(genre + " book \"" + title + "\" written by \"" + author + "\", published on " + publishDate); Console.WriteLine(description); } }
static void Main(string[] args) { ///////////////////////////////////////////////////////////////////// // Read XML document using the XmlTextReader class. // // The XmlTextReader acts as a reader pointer that only moves forward. // Because it always moves forward and read a piece of data into // memory buffer, it has better performance than the XmlDocument // class which loads the whole document into memory. Console.WriteLine("Loading XML using XmlTextReader..."); XmlTextReader xmlTextReader = new XmlTextReader(@"Books.xml"); xmlTextReader.WhitespaceHandling = WhitespaceHandling.None; while (xmlTextReader.Read()) { if (xmlTextReader.Name == "book") { Console.WriteLine(xmlTextReader.GetAttribute("id") + ": "); xmlTextReader.Read(); string author = xmlTextReader.ReadElementContentAsString(); string title = xmlTextReader.ReadElementContentAsString(); string genre = xmlTextReader.ReadElementContentAsString(); string price = xmlTextReader.ReadElementContentAsString(); string publishDate = xmlTextReader.ReadElementContentAsString(); string description = xmlTextReader.ReadElementContentAsString(); Console.WriteLine(genre + " book \"" + title + "\" written by \"" + author + "\", published on " + publishDate); Console.WriteLine(description); } } xmlTextReader.Close(); ///////////////////////////////////////////////////////////////////// // Read XML document using the XmlDocument and XmlNodeReader classes. // // XmlNodeReader is similar to XmlTextReader but accepts an XmlNode // instance as target to read. The following code shows how to use // XmlDocument and XmlNodeReader to retrieve XML information. It is // also a forward-only reader. Console.WriteLine("Loading XML using XmlDocument & XmlNodeReader..."); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(@"Books.xml"); XmlNodeList xmlNodes = xmlDocument.GetElementsByTagName("book"); foreach (XmlNode node in xmlNodes) { Console.WriteLine(node.Attributes["id"].Value + ":"); XmlNodeReader xmlNodeReader = new XmlNodeReader(node); xmlNodeReader.Read(); xmlNodeReader.Read(); string author = xmlNodeReader.ReadElementContentAsString(); string title = xmlNodeReader.ReadElementContentAsString(); string genre = xmlNodeReader.ReadElementContentAsString(); string price = xmlNodeReader.ReadElementContentAsString(); string publishDate = xmlNodeReader.ReadElementContentAsString(); string description = xmlNodeReader.ReadElementContentAsString(); Console.WriteLine(genre + " book \"" + title + "\" written by \"" + author + "\", published on " + publishDate); Console.WriteLine(description); } ///////////////////////////////////////////////////////////////////// // Make changes to the XmlDocument. // // Modify a node value by first calling SelectSingleNode to navigate // to that node and by setting its InnerText property to change its // content. XmlNode nodeToModify = xmlDocument.DocumentElement.SelectSingleNode( "book/genre"); nodeToModify.InnerText = "XML Tech"; // Add a new XML node. In XML programming, we always call // XMLDocument.Create*** to create an attribute or element. After // that, we can add it into where we want by calling Node.AppendChild XmlElement newElement = xmlDocument.CreateElement("book"); XmlAttribute newAttribute = xmlDocument.CreateAttribute("id"); newAttribute.Value = "bk103"; XmlElement authorElement = xmlDocument.CreateElement("author"); authorElement.InnerText = "Mark Russinovich,David Solomon,Alex Ionecsu"; XmlElement titleElement = xmlDocument.CreateElement("title"); titleElement.InnerText = "Windows Internals, 5th edition"; XmlElement genreElement = xmlDocument.CreateElement("genre"); genreElement.InnerText = "Windows Server 2008"; XmlElement priceElement = xmlDocument.CreateElement("price"); priceElement.InnerText = "69.99"; XmlElement publishDateElement = xmlDocument.CreateElement("publish_date"); publishDateElement.InnerText = "2009-6-17"; XmlElement descriptionElement = xmlDocument.CreateElement("description"); descriptionElement.InnerText = "Windows Internals, 5th edition is the" + " update to Windows Internals, 4th edition to cover Windows Vista" + " and Windows Server 2008 (32-bit and 64-bit)."; newElement.Attributes.Append(newAttribute); newElement.AppendChild(authorElement); newElement.AppendChild(titleElement); newElement.AppendChild(genreElement); newElement.AppendChild(priceElement); newElement.AppendChild(publishDateElement); newElement.AppendChild(descriptionElement); xmlDocument.DocumentElement.AppendChild(newElement); // Save the changes xmlDocument.Save("Modified Books.xml"); // XmlLDocument does not have Close or Dispose method because it is // an in-memory representation of an XML document. Once read, the // file is no-longer needed. }
public void importaSessao(DateTime data) { try { using (AuditoriaEntities db = new AuditoriaEntities()) { SessoesReunioes cliente = new SessoesReunioes(); sessao_camara sessao = new sessao_camara(); List <sessao_camara> sessoes = new List <sessao_camara>(); XmlNode resposta = cliente.ListarPresencasDia(data.Date.ToString("dd/MM/yyyy", CultureInfo.CurrentCulture), "", "", ""); XmlNodeReader reader = new XmlNodeReader(resposta); int qtdSessoaDia = 0; reader.Read(); //header reader.Read(); //dia if (reader.NodeType.ToString() != "None") { sessao.dataSessao = data; //data reader.Read(); reader.Read(); reader.Read(); qtdSessoaDia = reader.ReadElementContentAsInt(); //qtdeSessoes sessao.legislatura = reader.ReadElementContentAsInt(); //legislatura //Verifica se o dia já foi importado var dataverify = from d in db.sessoes_camara .Where(d => d.dataSessao == sessao.dataSessao) select d; if (!(dataverify.Count() > 0)) { reader.Read(); //parlamentar while (reader.Name != "sessaoDia") { reader.Read(); } for (int i = 0; i < qtdSessoaDia; i++) { reader.Read(); sessao.inicio = reader.ReadElementContentAsString(); sessao.inicio = sessao.inicio.Substring(sessao.inicio.IndexOf(" ") + 1, (sessao.inicio.Length - sessao.inicio.IndexOf(" ") - 1)); string desc = reader.ReadElementContentAsString(); sessao.descricao = desc.Substring(0, desc.IndexOf("-") - 1); reader.Read(); reader.Read(); reader.Read(); reader.Read(); sessoes.Add(new sessao_camara() { dataSessao = sessao.dataSessao, descricao = sessao.descricao, inicio = sessao.inicio, legislatura = sessao.legislatura, }); sessoes[i] = db.sessoes_camara.Add(sessoes[i]); db.SaveChangesAsync(); } importaPresenca(resposta, db, sessoes); } } else { } } } catch (DbEntityValidationException e) { //gerar log foreach (var eve in e.EntityValidationErrors) { Console.WriteLine(eve.Entry.Entity.GetType().Name + ": \n"); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("-- " + ve.ErrorMessage + "\n"); } } } catch (Exception ex) { //gerar log Console.WriteLine(ex.Message + "\n"); Console.WriteLine(ex.TargetSite + "\n"); Console.WriteLine(ex.StackTrace); Console.Read(); } }
private void importaPresenca(System.Xml.XmlNode resultado, AuditoriaEntities db, List <sessao_camara> sessoes) { try { XmlNodeReader reader = new XmlNodeReader(resultado); presenca_deputado presenca = new presenca_deputado(); bool fim = false; while (reader.LocalName != "carteiraParlamentar") { reader.Read(); } while (fim == false) { presenca.legislatura = sessoes[0].legislatura; presenca.carteiraParlamentar = reader.ReadElementContentAsInt(); while (reader.LocalName != "justificativa") { reader.Read(); } presenca.justificativa = reader.ReadElementContentAsString(); presenca.presencaExterna = (sbyte)reader.ReadElementContentAsInt(); reader.Read(); while (reader.LocalName != "sessoesDia") { reader.Read(); reader.Read(); reader.Read(); reader.Read(); string descricao = reader.ReadElementContentAsString(); descricao = descricao.Substring(0, descricao.IndexOf("-") - 1); var verify = from b in sessoes.Where(b => b.descricao == descricao) select b; presenca.idSessao = verify.ElementAt(0).idSessao; if (reader.ReadElementContentAsString() == "Presença") { presenca.presenca = 1; } else { presenca.presenca = 0; } db.presencas_deputado.Add(presenca); db.SaveChangesAsync(); reader.Read(); } reader.Read(); reader.Read(); reader.Read(); if (reader.NodeType.ToString() == "EndElement") { fim = true; } } } catch (Exception ex) { Console.WriteLine(ex.Message + "\n"); Console.WriteLine(ex.TargetSite + "\n"); Console.WriteLine(ex.StackTrace); Console.ReadLine(); } }