= Using XML = Editing XML Normally, binding a ListView to a datasource (the xml) and let WPF databinding handle the update of the XML data automatically. To do this you could create a [[http://msdn.microsoft.com/en-us/library/84sxtbxh(VS.80).aspx|DataSet from your XML]] and then bind that using ListView.ItemsSource. You would then create a DataTemplate to define the visual representation of a record in your xml. This could be input controls that'd allow you do directly edit the record within your listview. If you prefer a master-detail style view you would bing the detail view to the current item of your listview (e.g. UserControl.DataContext={Binding CurrentItem, ElementName=myListView}). The rest will be handled by WPF. UPDATE: Here is an [[http://msdn.microsoft.com/en-us/library/cc165615.aspx|example]] how you could even bind directly to your XDocument, so so you do not necessarily have to use DataSets. (Source: [[http://stackoverflow.com/questions/1659734/wpf-and-c-gridview-row-selection-and-xml-datasource-how-to-make-the-connecti|bitbonk on StackOverflow.com]]) == Parsing XML == Example (Source: [[http://stackoverflow.com/questions/55828/best-practices-to-parse-xml-files|Lukas Šalkauskas]]): XmlDocument xmlDoc= new XmlDocument(); //* create an xml document object. xmlDoc.Load("yourXMLFile.xml"); //* load the XML document from the specified file. //* Get elements. XmlNodeList girlAddress = xmlDoc.GetElementsByTagName("gAddress"); XmlNodeList girlAge = xmlDoc.GetElementsByTagName("gAge"); XmlNodeList girlCellPhoneNumber = xmlDoc.GetElementsByTagName("gPhone"); //* Display the results. Console.WriteLine("Address: " + girlAddress[0].InnerText); Console.WriteLine("Age: " + girlAge[0].InnerText); Console.WriteLine("Phone Number: " + girlCellPhoneNumber[0].InnerText); XmlDocument: If you are after one specific element, you can access child elements with the indexer: xmlDoc["Root"], and these can be chained: xmlDoc["Root"]["Folder"]["Item"] to dig down the hierarchy (although it's sensible to validate that these elements actually exist) – ([[http://stackoverflow.com/questions/55828/best-practices-to-parse-xml-files|Source: Jason Williams]]) If you're processing a large amount of data (many megabytes) then you want to be using XmlReader to stream parse the XML. Anything else (XPathNavigator, XElement, XmlDocument and even XmlSerializer if you keep the full generated object graph) will result in high memory usage and also a very slow load time. Of course, if you need all the data in memory anyway, then you may not have much choice. ([[http://stackoverflow.com/questions/55828/best-practices-to-parse-xml-files|Source: Simon Steele]]) Other technologies and libraries to manipulate XML in .NET: * [[http://msdn.microsoft.com/en-us/library/system.xml.xmltextreader(VS.80).aspx|XmlTextReader]] * [[http://msdn.microsoft.com/en-us/library/system.xml.xmlreader(VS.80).aspx|XmlReader]] * [[http://msdn.microsoft.com/en-us/library/system.xml.xmlnodereader(VS.80).aspx|XmlNodeReader]] * [[http://msdn.microsoft.com/en-us/library/system.xml.xpath(VS.80).aspx|System.Xml.XPath]] * [[http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator(VS.80).aspx|XPathNavigator]] * [[http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathdocument(VS.80).aspx|XPathDocument]] * [[http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathexpression(VS.80).aspx|XPathExpression]] * [[http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnodeiterator(VS.80).aspx|XPathnodeIterator]] * [[http://msdn.microsoft.com/en-us/library/bb387098.aspx|LINQ to XML]] * [[http://msdn.microsoft.com/en-us/library/182eeyhh.aspx|Intro to XML Serialization]] == Using LINQ with XML == Example: (Source: [[http://stackoverflow.com/questions/1659734/wpf-and-c-gridview-row-selection-and-xml-datasource-how-to-make-the-connecti|StackOverflow.com]]) XDocument xml = XDocument.Load(@"D:\devel\VS\pchart\charts.xml"); var query = from p in xml.Elements("charts").Elements("chart") select p; foreach (var record in query) { chartListView.Items.Add(new { Name = record.Attribute("Name").Value, Type = record.Attribute("Type").Value, defaultFontName = record.Attribute("defaultFontName").Value, defaultFontSize = record.Attribute("defaultFontSize").Value, ID = record.Attribute("ID").Value } ); } Converting between List and IEnumerable: ([[http://stackoverflow.com/questions/472669/c-freely-convert-between-listt-and-ienumerablet|Source: DrJokepu]]) List myList = new List(); IEnumerable myEnumerable = myList; List listAgain = myEnumerable.ToList(); Beware however that myEnumarable is the same object instance as myList, but listAgain is not the same object instance as myEnumerable. Depending on what you want to do and what myEnumerable is, ''"List listAgain = myEnumerable as List;"'' might be better. – ChrisW Chrisw: Oh yes, you're right of course, but the ''IEnumerable'' interface is immutable so it will not cause problems in that direction and casting back just feels dirty when you have a function that will take care of type safety. – DrJokepu You also could just use the original myList object. (I guess I don't really get the question) – sth It's just that if he edits myList then he would be editing myEnumrable, but if he edits listAgain then he wouldn't be editing myEnumerable. A ''List'' is an ''IEnumerable'', so actually, there's no need to 'convert' a ''List'' to an ''IEnumerable''. Since a ''List'' is an ''IEnumerable'', you can simply assign a ''List'' to a variable of type ''IEnumerable''. The other way around, not every ''IEnumerable'' is a ''List'' of course, so then you'll have to call the ''ToList()'' member method of the ''IEnumerable''. Source: [[http://stackoverflow.com/questions/472669/c-freely-convert-between-listt-and-ienumerablet|David B, Frederik Gheysels]] = Examples = == Loading and Parsing an XML File into a Data Structure == For an XML file like this: Acme's 12th Annual Continuing Education Workshop 12 AcmeWorkshop12 Orlando Marriott Lake Mary 1501 International Parkway Lake Mary FL 32746 407.995.1100 800.380.7724 407.995.1101 www.marriotthotels.com 2008-06-11 2008-06-12 Premium 100 Standard 200 Other 200 Acme's 13th Annual Continuing Education Workshop 13 AcmeWorkshop13 Orlando Marriott Lake Mary 1501 International Parkway Lake Mary FL 32746 407.995.1100 800.380.7724 407.995.1101 www.marriotthotels.com 2009-06-15 2009-06-16 Premium 100 Standard 200 Other 200 To format XML content to fit in a data structure like this: //======================================================================== // Class TWorkshop //======================================================================== public class TWorkshop { public int RecID { get; set; } public string WorkshopID { get; set; } public string Name { get; set; } public TContactInfo VenueInfo { get; set; } public List Days { get; set; } public List PricingDailyPackages { get; set; } public string CancellationPolicy { get; set; } public string Instructions { get; set; } public string HotelAccommodations { get; set; } } We can implement the logic in a function like this: //----------------------------------------------------------------------------------------- /// /// Load data from an XML file. /// /// Filename of XML file to load /// true if success, false if not //----------------------------------------------------------------------------------------- public bool LoadFromXmlFile(string AFilename) { if (System.IO.File.Exists(AFilename)) { xmldoc = XDocument.Load(AFilename); if (xmldoc != null) { // parse xml data and load into TWorkshopList object List xmldata = new List(); xmldata = xmldoc.Root.Elements("Workshop").ToList(); foreach (XElement el in xmldata) { // create TWorkshop record TWorkshop currec = new TWorkshop(); // Parse xml record, and add it currec.VenueInfo.Clear(); currec.Name = el.Element("Name").Value; currec.WorkshopID = el.Element("WorkshopID").Value; currec.RecID = Convert.ToInt32(el.Element("RecID").Value); currec.VenueInfo.Organization = el.Element("VenueInfo").Element("Organization").Value; currec.VenueInfo.Address.AddressLn1 = el.Element("VenueInfo").Element("AddressLn1").Value; currec.VenueInfo.Address.City = el.Element("VenueInfo").Element("City").Value; currec.VenueInfo.Address.StateProv = el.Element("VenueInfo").Element("StateProv").Value; currec.VenueInfo.Address.PostalCode = el.Element("VenueInfo").Element("PostalCode").Value; currec.VenueInfo.PhoneHome = el.Element("VenueInfo").Element("PhoneHome").Value; currec.VenueInfo.PhoneWork = el.Element("VenueInfo").Element("PhoneWork").Value; currec.VenueInfo.Fax = el.Element("VenueInfo").Element("Fax").Value; currec.VenueInfo.Website = el.Element("VenueInfo").Element("Website").Value; currec.CancellationPolicy = el.Element("CancellationPolicy").Value; currec.Instructions = el.Element("Instructions").Value; currec.HotelAccommodations = el.Element("HotelAccommodations").Value; // Days: extra processing currec.Days.Clear(); List elDays = el.Element("Days").Elements("DateTime").ToList(); foreach (XElement elDay in elDays) { string DateInInvariantCultureStrFmt = elDay.Value; DateTime DateLocalized = new DateTime(); try { DateLocalized = DateTime.Parse(DateInInvariantCultureStrFmt, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None); } catch(FormatException exc) { throw new FormatException(string.Format("'{0}' is not in an acceptable format. [{1}]", DateInInvariantCultureStrFmt, exc.Message)); } currec.Days.Add(DateLocalized); } // PricingDailyPackages: extra processing currec.PricingDailyPackages.Clear(); List elPkgs = el.Element("PricingDailyPackages").Elements("PricingPackage").ToList(); foreach (XElement elPkg in elPkgs) { TPricingPackage pkg = new TPricingPackage(); pkg.Name = elPkg.Element("Name").Value; pkg.Pricing = Convert.ToInt32(elPkg.Element("Pricing").Value); currec.PricingDailyPackages.Add(pkg); } // add TWorkshop record this.Add(currec); } // Success return true; } else { // Failed to load data from file return false; } } else { // Failed. File not found. return false; } } == Example using XmlDocument, XmlElement, XmlNodeList == Sample Data: . . . . . . . . . . . . . . . . . . . . . Code to load Xml document: ///---------------------------------------------------------------------------------------- /// /// Load data from XML file. /// /// ///---------------------------------------------------------------------------------------- public void LoadFromXml(string FileName) { // using System.Xml; XmlDocument xmlDoc = new XmlDocument(); // create an xml document object. xmlDoc.Load(FileName); // load the XML document from the specified file. try { for (int side = 0; side < 2; side++) { // Get elements. //XmlNodeList ParamConfigLst = xmlDoc["FittingSession"]["Instruments"]["Instrument"]["ParametersConfig"].GetElementsByTagName("Param"); //XmlNodeList ParamMemoryLst = xmlDoc["FittingSession"]["Instruments"]["Instrument"]["ParametersMemory"].GetElementsByTagName("Param"); //XmlNodeList ParamCustomLst = xmlDoc["FittingSession"]["Instruments"]["Instrument"]["ParametersCustom"].GetElementsByTagName("Param"); XmlNodeList HI = xmlDoc["FittingSession"]["Instruments"].GetElementsByTagName("Instrument"); XmlNodeList AutofitEnv = HI[side].ChildNodes[0].ChildNodes; XmlNodeList ParamConfigLst = HI[side].ChildNodes[1].ChildNodes; XmlNodeList ParamCustomLst = HI[side].ChildNodes[2].ChildNodes; XmlNodeList ParamMemoryLst = HI[side].ChildNodes[3].ChildNodes; // load data into package LoadXmlNodeListToIntArray(AutofitEnv, m_InstrumentParams[side].AutofitEnvironments); LoadXmlNodeListToDevParamList(ParamConfigLst, m_InstrumentParams[side].ParametersConfig); LoadXmlNodeListToDevParamList(ParamCustomLst, m_InstrumentParams[side].ParametersCustom); LoadXmlNodeListParamMemToDevParamList(ParamMemoryLst, m_InstrumentParams[side].ParametersMemory); } } catch (Exception exc) { TAppLog.LogException("TFittingSession.LoadFromXml", exc); } } ///---------------------------------------------------------------------------------------- /// /// Load Xml node list to Device Parameter list. /// /// /// ///---------------------------------------------------------------------------------------- private void LoadXmlNodeListToIntArray(XmlNodeList srcParamDataLst, int[] dstIntArray) { int CurAutofitEnvMemIdx = 0; for (int i = 0; i < srcParamDataLst.Count; i++) { CurAutofitEnvMemIdx = Convert.ToInt32(srcParamDataLst[i].Attributes["Memory"].InnerText); dstIntArray[CurAutofitEnvMemIdx] = Convert.ToInt32(srcParamDataLst[i].Attributes["Index"].InnerText); } } ///---------------------------------------------------------------------------------------- /// /// Load Xml node list to Device Parameter list. /// /// /// ///---------------------------------------------------------------------------------------- private void LoadXmlNodeListToDevParamList(XmlNodeList srcParamDataLst, TDevParamList dstParamDataLst) { for (int i = 0; i < srcParamDataLst.Count; i++) { dstParamDataLst.Add(new TDevParam() { Name = srcParamDataLst[i].Attributes["Name"].InnerText, Value = Convert.ToInt32(srcParamDataLst[i].Attributes["Value"].InnerText) }); } } ///---------------------------------------------------------------------------------------- /// /// Load Xml node list to Device Parameter list. /// /// /// ///---------------------------------------------------------------------------------------- private void LoadXmlNodeListParamMemToDevParamList(XmlNodeList srcParamMemLst, TDevParamList[] dstParamMemLst) { // Format: // // ... // ... // ... // ... // XmlNodeList[] MemParams = new XmlNodeList[srcParamMemLst.Count]; for (int mem = 0; mem < MemParams.Length; mem++) { MemParams[mem] = srcParamMemLst.Item(mem).ChildNodes; for (int paramidx = 0; paramidx < MemParams[mem].Count; paramidx++) { dstParamMemLst[mem].Add(new TDevParam() { Name = MemParams[mem][paramidx].Attributes["Name"].InnerText, Value = Convert.ToInt32(MemParams[mem][paramidx].Attributes["Value"].InnerText) }); } } } ///---------------------------------------------------------------------------------------- /// /// Get the Xml node list of requested tag name for the given Xml document section. /// /// /// /// /// ///---------------------------------------------------------------------------------------- private XmlNodeList GetElements(XmlDocument xmlDoc, string SectionName, string ElementTagName) { //XmlNode xmlnodeSection = xmlDoc.GetElementsByTagName(SectionName)[0]; // get section tree (eg: Data3) XmlNode xmlnodeSection = xmlDoc.GetElementsByTagName(SectionName)[0]; // get section tree (eg: Data3) // Convert Section xmlnode into Section xmldoc // 1. Create empty xmldoc // 2. Import Section xmlnode into it. XmlDocument xmldocSection = new XmlDocument(); xmldocSection.LoadXml(""); // load DocumentType XmlNode xn = xmldocSection.ImportNode(xmlnodeSection, true /* deep */); // import node xmldocSection.DocumentElement.AppendChild(xn); // associate imported node into correct hierarchy position // Search for requested Elements in this Section return xmldocSection.GetElementsByTagName(ElementTagName); // search for child nodes == Param } = References = * [[http://msdn.microsoft.com/en-us/library/cc165615.aspx|MSDN: How To: Bind to XDocument, XElement, or LINQ for XML Query Results]] * [[http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx|MSDN: XElement Class]] * [[http://support.microsoft.com/kb/301233|MSDN: How to Modify ans Save XML with XmlDocument Class]] * [[http://joshsmithonwpf.wordpress.com/2007/06/04/binding-to-xml|Josh Smith on WPF: Binding to XML]] * [[http://dotnet.dzone.com/articles/data-binding-wpf-binding-xml|Data Binding with WPF: Binding to XML]] * [[http://www.hookedonlinq.com/Print.aspx?Page=LINQtoXML5MinuteOverview|LINQ to XML - 5 Minute Overview]] * [[http://msdn.microsoft.com/en-us/library/system.xml.linq.xnode.nextnode.aspx|MSDN: XNode.NextNode]]