private string mNiceName; // nice name for the script itself public ScriptParser(string ScriptPath) { mParameterList = new List <ScriptParameter>(); mScriptFilePath = ScriptPath; XmlTextReader reader = new XmlTextReader(mScriptFilePath); reader.XmlResolver = null; XmlDataDocument doc = new XmlDataDocument(); doc.XmlResolver = null; doc.Load(reader); reader.Close(); XmlNode taskScriptNode = doc.DocumentElement; if (taskScriptNode.Attributes.GetNamedItem("name") != null) { m_Name = taskScriptNode.Attributes.GetNamedItem("name").Value; } mNiceName = GetScriptNiceName(doc, mScriptFilePath); PopulateParameterList(doc); }
public void GetElementFromRow() { XmlDataDocument doc = new XmlDataDocument(); doc.DataSet.ReadXmlSchema("Test/System.Xml/region.xsd"); doc.Load("Test/System.Xml/region.xml"); DataTable table = doc.DataSet.Tables ["Region"]; XmlElement element = doc.GetElementFromRow(table.Rows [2]); Assert.AreEqual("Region", element.Name, "#D01"); Assert.AreEqual("3", element ["RegionID"].InnerText, "#D02"); try { element = doc.GetElementFromRow(table.Rows [4]); Assert.Fail("#D03"); } catch (IndexOutOfRangeException e) { Assert.AreEqual(typeof(IndexOutOfRangeException), e.GetType(), "#D04"); Assert.AreEqual("There is no row at position 4.", e.Message, "#D05"); } }
/// <summary> /// Imports the Xml-File and creates the Setting /// </summary> public static Location ImportFile(string filename, TextBox display) { XmlDataDocument xml = new XmlDataDocument(); FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read); xml.Load(fs); Location output = new Location(); output.Display = display; output.Protagonist = ImportProtagonist(xml); output.Rooms.AddRange(ImportRooms(xml)); output.Implements.AddRange(ImportImplements(xml)); output.Clothes.AddRange(ImportClothes(xml)); output.Holdings.AddRange(ImportHoldings(xml)); output.Girls.AddRange(ImportGirls(xml)); output.Pool = ImportMessages(xml); output.Prepare(); return(output); }
/// <summary> /// Determines if we need to save the definition. /// Logic :: compares wf compilation time, with AsmCreateDate on wf def file /// if AsmCreateDate !=Wf assembly compilation time, we will load it /// </summary> /// <returns>true/false</returns> public bool IsNewOrUpdatedWfDefinition(Activity rootActivity) { if (!File.Exists(_workflowDefPath)) { return(true); } else { XmlDataDocument xmldoc = new XmlDataDocument(); xmldoc.LoadXml(GetWorkflowDefinitionString()); XmlNodeList rootActivities = xmldoc.SelectNodes("/Activity"); if (rootActivities != null) { DateTime savedWfCompliteTime = DateTime.Parse(rootActivities[0].Attributes["WfCompliteTime"].Value); return(!GetWfCompilationTimestamp(rootActivity) .Equals(savedWfCompliteTime)); } return(true); } }
public XmlElement GetUserDetails(string userName) { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString()); con.Open(); SqlCommand cmd = new SqlCommand("select * from padron where Apellido like @userName+'%'", con); cmd.Parameters.AddWithValue("@userName", userName); cmd.ExecuteNonQuery(); SqlDataAdapter da = new SqlDataAdapter(cmd); // Create an instance of DataSet. DataSet ds = new DataSet(); da.Fill(ds); con.Close(); // Return the DataSet as an XmlElement. XmlDataDocument xmldata = new XmlDataDocument(ds); XmlElement xmlElement = xmldata.DocumentElement; return(xmlElement); }
public void ParseSchema(ref XmlDataDocument document, string schema) { StreamReader myStreamReader = null; try { myStreamReader = new StreamReader(schema); document.DataSet.ReadXmlSchema(myStreamReader); } catch (Exception e) { Console.WriteLine("Exception during XSD Parsing: " + e.Message); } finally { if (myStreamReader != null) { myStreamReader.Close(); } } }
public void ReadSiteMap( ) { XmlDataDocument xmldoc = new XmlDataDocument(); XmlNodeList xmlnode; int i = 0; List <Dictionary <string, string> > lst = new List <Dictionary <string, string> >(); string str = null, path = AppDomain.CurrentDomain.BaseDirectory + @"Content\files\sitemap.xml"; FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); xmldoc.Load(fs); xmlnode = xmldoc.GetElementsByTagName("url"); for (i = 0; i <= xmlnode.Count - 1; i++) { Dictionary <string, string> item = new Dictionary <string, string>(); item["Path"] = xmlnode[i].ChildNodes.Item(0).InnerText.Trim(); item["Date"] = xmlnode[i].ChildNodes.Item(1).InnerText.Trim(); item["Priority"] = xmlnode[i].ChildNodes.Item(2).InnerText.Trim(); lst.Add(item); } ViewBag.SiteMap = lst; }
public static void XmlDataDocument_LoadXmlReader() { string xml = "<CustomTypesData>" + Environment.NewLine + "<CustomTypesTable>" + Environment.NewLine + "<Dummy>99</Dummy>" + Environment.NewLine + "</CustomTypesTable>" + Environment.NewLine + "</CustomTypesData>" + Environment.NewLine; StringReader sr = new StringReader(xml); XmlReader xr = new XmlTextReader(sr); XmlDataDocument doc = new XmlDataDocument(); doc.Load(xr); var nodeList = doc.GetElementsByTagName("CustomTypesData"); Assert.NotNull(nodeList); Assert.Equal(1, nodeList.Count); Assert.True(nodeList[0].HasChildNodes); Assert.Equal("CustomTypesData", nodeList[0].Name); }
public XmlDataDocument getLinkSpaceXml(int pageIndex, int recNo) { string query = getSQL(pageIndex, recNo, 0); SqlConnection conn = Connection.GetConnection(); //Create a DataAdapter to load data from original data source to the DataSet DataSet dataset = new DataSet("root"); dataset.EnforceConstraints = false; SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = new SqlCommand(query, conn); conn.Open(); adapter.Fill(dataset, "data"); //Create a virtual XML document on top of the DataSet XmlDataDocument doc = new XmlDataDocument(dataset); return(doc); }
/// <summary> Returns a semantic equivalent of a given XML-encoded message in a default format. /// Attributes, comments, and processing instructions are not considered to change the /// HL7 meaning of the message, and are removed in the standardized representation. /// </summary> public static System.String standardizeXML(System.String message) { System.Xml.XmlDocument doc = null; System.IO.StringWriter out_Renamed = new System.IO.StringWriter(); try { lock (parser) { XmlTextReader reader = new XmlTextReader(new System.IO.MemoryStream(new System.Text.ASCIIEncoding().GetBytes(message))); System.Data.DataSet data = new System.Data.DataSet(); data.ReadXml(reader); doc = new XmlDataDocument(data); } clean((System.Xml.XmlElement)doc.DocumentElement); } catch (System.IO.IOException e) { throw new System.SystemException("IOException doing IO to a string!!! " + e.Message); } return(out_Renamed.ToString()); }
public XmlDocument AllNewsDetails(string var) { DataSet ds = new DataSet(); XmlDataDocument xmldatadoc = new XmlDataDocument(); try { string sql; sql = "select [NHeading],[NTopic],[NPaper],[DONR],[LDOA],[NFeesApp],[NInDetail],[NApplicablefor],[NState],[NDistrict],[NCity] FROM [Come2myCityDB].[come2mycity].[tblShowNews] where [NCurrentDate]>='" + var + "' "; ds = cc.ExecuteDataset(sql); if (ds.Tables[0].Rows.Count > 0) { xmldatadoc = new XmlDataDocument(ds); XmlElement xmlelement = xmldatadoc.DocumentElement; } } catch (Exception ex) { } return(xmldatadoc); }
public void CloneNode() { XmlDataDocument doc = new XmlDataDocument(); doc.DataSet.ReadXmlSchema("Test/System.Xml/region.xsd"); doc.Load("Test/System.Xml/region.xml"); XmlDataDocument doc2 = (XmlDataDocument)doc.CloneNode(false); Assert.AreEqual(0, doc2.ChildNodes.Count, "#I01"); Assert.AreEqual("<?xml version=\"1.0\" encoding=\"utf-16\"?>", doc2.DataSet.GetXmlSchema().Substring(0, 39), "#I02"); doc2 = (XmlDataDocument)doc.CloneNode(true); Assert.AreEqual(2, doc2.ChildNodes.Count, "#I03"); Assert.AreEqual("<?xml version=\"1.0\" encoding=\"utf-16\"?>", doc2.DataSet.GetXmlSchema().Substring(0, 39), "#I04"); doc.DataSet.Tables [0].Rows [0][0] = "64"; Assert.AreEqual("1", doc2.DataSet.Tables [0].Rows [0][0].ToString(), "#I05"); }
//https://www.ines.gov.br/dicionario-de-libras/main_site/filme/ public static void ObterVideos() { XmlDataDocument xmldoc = new XmlDataDocument(); int i = 0; string str = null; FileStream fs = new FileStream(@"D:\Code\TioRAC\Equipe6\Equipe6Console\Libras\palavras.xml", FileMode.Open, FileAccess.Read); xmldoc.Load(fs); var xmlnode = xmldoc.GetElementsByTagName("banco")[0]; foreach (XmlElement child in xmlnode) { Console.WriteLine("Downlod file: " + child.Attributes["p"].Value); var video = child.Attributes["f"].Value; using (var client = new WebClient()) { client.DownloadFile("https://www.ines.gov.br/dicionario-de-libras/main_site/filme/" + video, @"D:\Teste\LibrasVideos\ines\" + video); } } }
public void Run(String args) { try { // Load the XML from file Console.WriteLine(); Console.WriteLine("Loading file {0} ...", args); XmlDataDocument myXmlDocument = new XmlDataDocument(); myXmlDocument.Load(args); Console.WriteLine("XmlDataDocument loaded with XML data successfully ..."); // Display the XML document. myXmlDocument.Save(Console.Out); } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } }
static void Main(string[] args) { string strConn = "Data Source=localhost;Initial Catalog=booksourcedb;Integrated Security=True"; string strSql = "SELECT * FROM book"; SqlDataAdapter dataAdapter = new SqlDataAdapter(strSql, strConn); DataSet dataSet = new DataSet("booklist"); dataAdapter.Fill(dataSet, "book"); XmlDataDocument xdd = new XmlDataDocument(dataSet); string xpath = "/booklist/book[bid='b2']"; XmlElement eBook = (XmlElement)xdd.SelectSingleNode(xpath); Console.WriteLine("bid = " + eBook.ChildNodes[0].InnerText); Console.WriteLine("kind = " + eBook.ChildNodes[1].InnerText); Console.WriteLine("title = " + eBook.ChildNodes[2].InnerText); Console.WriteLine("publisher = " + eBook.ChildNodes[3].InnerText); Console.WriteLine("price = " + eBook.ChildNodes[4].InnerText); }
/// <summary> /// Parses the content. /// </summary> /// <param name="printContext">The print context.</param> /// <returns> /// The content. /// </returns> protected virtual string ParseContent(PrintContext printContext) { Assert.IsNotNull(this.ContentItem, "Content item is null"); Assert.IsNotNullOrEmpty(this.ContentFieldName, "Missing content field"); Field contentField = this.ContentItem.Fields[this.ContentFieldName]; if (contentField == null) { return(string.Empty); } CustomField field = FieldTypeManager.GetField(contentField); if (field == null) { return(contentField.Value); } if (field is HtmlField) { Item defaultFormatting = printContext.Settings.GetDefaultFormattingItem(printContext.Database); if (defaultFormatting != null) { try { XmlDataDocument tempDoc = new XmlDataDocument(); return(PatternBuilder.TransformRichContent(field.Value, printContext.Database, tempDoc, defaultFormatting, "XHTML", "XML")); } catch (Exception exc) { Log.Error(exc.Message, this); } } return(PatternBuilder.RichTextToTextParser(field.Value, true, false)); } return(field.Value); }
public void CreateXml(DataSet dataset_for_index_doc, DataSet dataset_for_folder, string indexing, string fullPath, string filename, SqlConnection connection, string folderID, string docID) { string temp_string = System.IO.Path.GetExtension(filename); string output_filename = filename.Replace(temp_string, ".xml"); string temp_fullpath = string.Format("{0}\\{1}", fullPath, output_filename); //String SQLCommand = " select * from obj where parent_id =" + indexing ; DataRow[] indexRow = dataset_for_index_doc.Tables[0].Select("DocID = " + docID); XmlDataDocument doc = new XmlDataDocument(); XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); DataRow[] r = dataset_for_folder.Tables[0].Select("folderID = " + folderID); string temp_index_name = r[0].ItemArray[0].ToString().Replace(" ", ""); XmlElement element1 = doc.CreateElement(string.Empty, temp_index_name, string.Empty); doc.AppendChild(element1); //Create an element representing the first customer record. //foreach (DataRow row in ds.Tables[0].Rows) //{ // string temp_index_name1 = row.ItemArray[3].ToString().Replace(" ", ""); // XmlElement element2 = doc.CreateElement(string.Empty, temp_index_name1, string.Empty); // XmlText text1 = doc.CreateTextNode(row.ItemArray[3].ToString()); // element2.AppendChild(text1); // element1.AppendChild(element2); //} foreach (DataRow index in indexRow) { string temp_index_name1 = index.ItemArray[4].ToString().Replace(" ", ""); XmlElement element2 = doc.CreateElement(string.Empty, temp_index_name1, string.Empty); XmlText text1 = doc.CreateTextNode(index.ItemArray[3].ToString()); element2.AppendChild(text1); element1.AppendChild(element2); } doc.Save(temp_fullpath); }
// bug #54505 public void TypedDataDocument() { string xml = @"<top xmlns=""urn:test""> <foo> <s>first</s> <d>2004-02-14T10:37:03</d> </foo> <foo> <s>second</s> <d>2004-02-17T12:41:49</d> </foo> </top>"; string xmlschema = @"<xs:schema id=""webstore"" targetNamespace=""urn:test"" xmlns:xs=""http://www.w3.org/2001/XMLSchema""> <xs:element name=""top""> <xs:complexType> <xs:sequence maxOccurs=""unbounded""> <xs:element name=""foo""> <xs:complexType> <xs:sequence maxOccurs=""unbounded""> <xs:element name=""s"" type=""xs:string""/> <xs:element name=""d"" type=""xs:dateTime""/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>"; XmlDataDocument doc = new XmlDataDocument(); doc.DataSet.ReadXmlSchema(new StringReader(xmlschema)); doc.LoadXml(xml); DataTable foo = doc.DataSet.Tables ["foo"]; DataRow newRow = foo.NewRow(); newRow ["s"] = "new"; newRow ["d"] = DateTime.Now; foo.Rows.Add(newRow); doc.Save(new StringWriter()); }
//const System.Xml.XPath.XPathExpression XPATH_FAVORITES = System.Xml.XPath.XPathExpression.Compile(NODE_XPATH_FAVORITE_COLLECTION + @"\" + NODE_XPATH_FAVORITE_TAG); static FavoritesManagement() { string xPathFfavorites = NODE_XPATH_FAVORITE_COLLECTION + @"/" + NODE_XPATH_FAVORITE_TAG; XmlDocument doc = new XmlDataDocument(); try { doc.Load(FAVORITE_FILE); } catch (FileNotFoundException) { favorites = new List <KeyValuePair <string, string> >(0); return; } catch (XmlException) { favorites = new List <KeyValuePair <string, string> >(0); return; } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } //return; XmlNodeList nodes = doc.SelectNodes(xPathFfavorites); favorites = new List <KeyValuePair <string, string> >(nodes.Count); foreach (XmlNode n in nodes) { favorites.Add ( new KeyValuePair <string, string> ( n.Attributes[XML_ATTRIBUTE_LABEL].Value, n.Attributes[XML_ATTRIBUTE_PATH].Value ) ); } }
public TraversalForm() { InitializeComponent(); try { // Load the document XmlDataDocument doc = loadXML(); if (doc == null) { return; } // Traverse the document using relational calls m_strOutput += "***Retrieving Using Relational Calls***\r\n\r\n"; retrieveAsData(doc); // Traverse the document using DOM calls m_strOutput += "\r\n\r\n***Retrieving Using DOM Calls***\r\n\r\n"; retrieveAsXml(doc); // Show the document m_strOutput += "\r\n\r\n***The XMLDataDocument ***\r\n\r\n"; StringWriter writerString = new StringWriter(); XmlTextWriter writer = new XmlTextWriter(writerString); writer.Formatting = Formatting.Indented; doc.WriteTo(writer); writer.Flush(); m_strOutput += writerString.ToString(); textBox1.Text = m_strOutput; } catch (Exception exception) { MessageBox.Show(exception.Message); } }
public static void GetStringValueFromResource(string filePath, string targetLang, string destinationPath) { List <String> resxValue = new List <string>(); XmlDataDocument xmldoc = new XmlDataDocument(); XmlNodeList xmlnode; int i = 0; string strEng = string.Empty; List <string> strConverted = new List <string>(); FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite); xmldoc.Load(fs); xmlnode = xmldoc.GetElementsByTagName("value"); XmlNodeList aNodes = xmldoc.SelectNodes("/root/data/value"); foreach (XmlNode aNode in aNodes) { if (aNode.InnerText != null) { string currentValue = aNode.InnerText; if (currentValue.Contains("&")) { currentValue = currentValue.Replace("&", String.Empty); } if (!string.IsNullOrEmpty(currentValue)) { strConverted = Internalization.YandexTranslate.Translate(targetLang, currentValue); aNode.InnerText = strConverted[0]; } } } fs.Close(); if (destinationPath == string.Empty) { xmldoc.Save(Path.GetDirectoryName(filePath) + "\\" + Path.GetFileNameWithoutExtension(filePath) + "_" + targetLang + Path.GetExtension(filePath)); } else { xmldoc.Save(destinationPath + "_" + targetLang + Path.GetExtension(filePath)); } }
// Function : Export_with_XSLT_Windows // Arguments : dsExport, sHeaders, sFileds, FormatType, FileName // Purpose : Exports dataset into CSV / Excel format private void Export_with_XSLT_Windows(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName) { try { // XSLT to use for transforming this dataset. MemoryStream stream = new MemoryStream( ); XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8); CreateStylesheet(writer, sHeaders, sFileds, FormatType); writer.Flush( ); stream.Seek(0, SeekOrigin.Begin); XmlDocument xsl = new XmlDocument(); xsl.Load(stream); //XslTransform xslTran = new XslTransform(); //xslTran.Load(new XmlTextReader(stream), null, null); //System.IO.StringWriter sw = new System.IO.StringWriter(); //xslTran.Transform(xmlDoc, null, sw, null); XmlDataDocument xmlDoc = new XmlDataDocument(dsExport); StringWriter sw = new StringWriter(); XmlTextWriter xtw = new XmlTextWriter(sw); XslCompiledTransform t = new XslCompiledTransform(); t.Load((IXPathNavigable)xsl, null, null); t.Transform((IXPathNavigable)xmlDoc, xtw); //Writeout the Content File.WriteAllText(FileName, sw.ToString()); sw.Close(); xtw.Close(); writer.Close(); stream.Close(); sw.Dispose(); stream.Dispose(); } catch (Exception Ex) { throw Ex; } }
private void EncodeNodes(TreeViewItemCollection NColl, XmlElement myXML, XmlDataDocument myXMLobj) { foreach (TreeViewItem Itm in NColl) { XmlElement nx = myXMLobj.CreateElement("item"); nx.SetAttribute("Text", Itm.Text); nx.SetAttribute("Image", Itm.Image); nx.SetAttribute("Link", Itm.Link); nx.SetAttribute("TargetFrame", Itm.TargetFrame); nx.SetAttribute("Open", Itm.Open.ToString()); nx.SetAttribute("value", Itm.Value); nx.SetAttribute("Selector", Itm.Selector.ToString()); nx.SetAttribute("Selected", Itm.Selected.ToString()); nx.SetAttribute("OnClick", Itm.OnClick); nx.SetAttribute("LoadOnExpand", Itm.LoadOnExpand.ToString()); myXML.AppendChild(nx); if (Itm.Items.Count > 0) { EncodeNodes(Itm.Items, nx, myXMLobj); } } }
/* public string GetData(int value) * { * return string.Format("You entered: {0}", value); * } * * public CompositeType GetDataUsingDataContract(CompositeType composite) * { * if (composite == null) * { * throw new ArgumentNullException("composite"); * } * if (composite.BoolValue) * { * composite.StringValue += "Suffix"; * } * return composite; * }*/ public IDictionary <string, string> getCrimeData(String zipCode) { XmlDataDocument doc = new XmlDataDocument(); IDictionary <String, String> data = new Dictionary <String, String>(); String url = "https://azure.geodataservice.net/GeoDataService.svc/GetUSDemographics?includecrimedata=true&zipcode=" + zipCode; doc.Load(url); XmlNodeList elementList = doc.GetElementsByTagName("element"); XmlNode root = elementList[0]; //Display the contents of the child nodes. if (root.HasChildNodes) { for (int i = 0; i < root.ChildNodes.Count; i++) { data.Add(root.ChildNodes[i].Name, root.ChildNodes[i].InnerText); } } return(data); }
private void FindProducts_Click(object sender, EventArgs e) { //XmlReader xmlReader = XmlReader.Create("C:/Downloads/boyner_product.xml"); XmlDataDocument xmldoc = new XmlDataDocument(); XmlNodeList xmlnode; int i = 0; string str = null; FileStream fs = new FileStream(PathTextbox.Text, FileMode.Open, FileAccess.Read); xmldoc.Load(fs); xmlnode = xmldoc.GetElementsByTagName(ProductTagTextbox.Text); int errorproduct = int.Parse(ErrorLineTextbox.Text) - 1; for (i = 0; i <= xmlnode.Count - 1; i++) { if (i == errorproduct) { string productcode = xmlnode[i].ChildNodes.Item(0).InnerText.Trim(); errorlines.Items.Add(productcode); } } }
public void Clear() { if (whoIsUpdated == WhoIsUpdate.XmlDataDocument) { // не работает т.к. надо заново определять DataSet //For I As Integer = _ds.Tables(TableCommand).Rows.Count - 1 To 0 Step -1 // mDataSetTables(TableCommand).Rows.RemoveAt(I) //Next //mDataSetEnforceConstraints = False //xmlDataDoc.RemoveAll() //mDataSetEnforceConstraints = True xmlDataDoc = null; mDataSet = new DataSet(); InitializeDataset(); DataGridCommand.DataSource = GetDataTable(); } else { mDataSet.Tables[TableCommand].Rows.Clear(); } }
private static int[][] LevelReader(string path) { var xmldoc = new XmlDataDocument(); XmlNodeList xmlnode; string str = null; FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); xmldoc.Load(fs); xmlnode = xmldoc.GetElementsByTagName("level"); for (int i = 0; i <= xmlnode.Count - 1; i++) { xmlnode[i].ChildNodes.Item(0); str = xmlnode[i].ChildNodes.Item(0).InnerText.Trim(); } var res = Regex.Split(str, "\n"); char[][] char2dArray = new char[res.Length][]; for (int i = 0; i < res.Length; i++) { char2dArray[i] = res[i].Where(ch => ch != ',').ToArray(); } int[][] levelMatrix = new int[char2dArray.Length][]; for (int i = 0; i < char2dArray.Length; i++) { levelMatrix[i] = Array.ConvertAll(char2dArray[i], c => (int)Char.GetNumericValue(c) == 3 ? 1 : 0); } levelMatrix[1][1] = 2; levelMatrix[14][17] = 3; return(levelMatrix); }
public List <SinhVienClass> Load() { XmlDataDocument xmldoc = new XmlDataDocument(); XmlNodeList list; FileStream fs = new FileStream("sinhvien.xml", FileMode.Open, FileAccess.ReadWrite); xmldoc.Load(fs); fs.Close(); list = xmldoc.GetElementsByTagName("SinhVien"); List <SinhVienClass> ListSV = new List <SinhVienClass>(); for (int i = 0; i < list.Count; i++) { SinhVienClass cl = new SinhVienClass(list[i].ChildNodes.Item(0).InnerText.Trim(), list[i].ChildNodes.Item(1).InnerText.Trim(), Convert.ToDateTime(list[i].ChildNodes.Item(2).InnerText), list[i].ChildNodes.Item(3).InnerText.Trim() ); ListSV.Add(cl); } return(ListSV); }
protected void DoBinding() { try { if (this.RssUrl.Length == 0) { throw new ApplicationException("The RssUrl cannot be null."); } // create a DataTable and fill it with the RSS data, // then bind it to the Repeater control XmlDataDocument feed = new XmlDataDocument(); feed.Load(GetFullUrl(this.RssUrl)); XmlNodeList posts = feed.GetElementsByTagName("item"); DataTable table = new DataTable("Feed"); table.Columns.Add("Title", typeof(string)); table.Columns.Add("Description", typeof(string)); table.Columns.Add("Link", typeof(string)); table.Columns.Add("PubDate", typeof(DateTime)); foreach (XmlNode post in posts) { DataRow row = table.NewRow(); row["Title"] = post["title"].InnerText; row["Description"] = post["description"].InnerText.Trim(); row["Link"] = post["link"].InnerText; row["PubDate"] = DateTime.Parse(post["pubDate"].InnerText); table.Rows.Add(row); } dlstRss.DataSource = table; dlstRss.DataBind(); } catch (Exception) { this.Visible = false; } }
/// <summary> /// Evaluates the minimum value. /// </summary> /// <param name="t">Type to evaluate</param> /// <param name="dataSource">Data source</param> /// <param name="fieldName">Field name foe which the evaluation is made</param> /// <returns>XmlElement which contains the resulting field</returns> public object EvaluateMin <T>(T t, object dataSource, string fieldName) { DataTableQueryEvaluator eval = null; XmlElement element = null; try { eval = new DataTableQueryEvaluator(); XmlDataDocument xdoc = (XmlDataDocument)dataSource; DataRow row = (DataRow)eval.EvaluateMin <DataTable>(xdoc.DataSet.Tables[0], xdoc.DataSet.Tables[0], fieldName); element = xdoc.GetElementFromRow(xdoc.DataSet.Tables[0].Rows[eval.EvaluatorIndexes[0]]); return(element); } catch { throw; } }
public XElement Get(string query) { try { //if (!HttpContext.Current.User.Identity.IsAuthenticated) // return ErrorResult("Please sign in first"); var serviceConnectionString = ConfigurationManager.ConnectionStrings["DBService"]; if (serviceConnectionString == null) return ErrorResult("No 'DBService' connection string"); string connectionString = serviceConnectionString.ConnectionString; // Create a connection to the data source using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); if (connection.State != ConnectionState.Open) return ErrorResult("No open connection"); using (SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connection)) { // "Root" is the root element name using (DataSet dataSet = new DataSet("Root")) { // "Row" is the name of each row in the set int rowCount = dataAdapter.Fill(dataSet, "Row"); if (dataSet.Tables.Count > 0) { // Indicate we want columns mapped as Xml attributes instead of elements //j foreach (DataColumn column in dataSet.Tables[0].Columns) foreach (DataTable table in dataSet.Tables) foreach (DataColumn column in table.Columns) column.ColumnMapping = MappingType.Attribute; } // Convert the DataSet into an XElement #if true XElement element = XElement.Parse(dataSet.GetXml(), LoadOptions.None); #else XElement element = null; XmlDataDocument xmlDataDocument = new XmlDataDocument(dataSet); using (XmlNodeReader reader = new XmlNodeReader(xmlDataDocument)) element = element.Load(reader, LoadOptions.None); #endif return element; //return ErrorResult("Test"); } } } } catch (Exception ex) { return ErrorResult(ex.Message); //j + Environment.NewLine + Environment.NewLine + e.StackTrace); } }