C#C
C#3y ago
Curious

❔ XML Read XML and save as dictionary

Hi all. I want to read XML data and convert to a dictionary, I have given this go with:

This is how i write:
......Above
                XmlTextWriter writer = new XmlTextWriter(StoredDataFile, System.Text.Encoding.UTF8);
                writer.WriteStartDocument(true);
                writer.Formatting = Formatting.Indented;
                writer.Indentation = 2;
                writer.WriteStartElement(startingText);
                //write dict to xml
                foreach (KeyValuePair<string, bool> kvp in toWrite)
                {
                    writer.WriteStartElement("Values");
                    writer.WriteAttributeString("key", kvp.Key);
                    writer.WriteAttributeString("value", kvp.Value.ToString());
                    writer.WriteEndElement();
                }
......Below

This is how I am reading:
public static Dictionary<string, bool> ReadFromXML(string tagToRead)
        {
            Dictionary<string, bool> outDict = new Dictionary<string, bool>();
            //look for the tag tagtoread in the XML tree, then return all values in that tag as a dictionary
            try
            {
                XDocument doc = XDocument.Load(StoredDataFile);
                XElement root = doc.Root;
                var values = doc.Root.Elements(tagToRead).Select(n => n.Value);
                
                //iterate through and get name and value to add to dictionary
                foreach (var value in values)
                {
                    string[] split = value.Split(',');
                    outDict.Add(split[0], Convert.ToBoolean(split[1]));
                }   
                return outDict;

            }
            catch (Exception ex)
            {
                Autodesk.Revit.UI.TaskDialog.Show("Read XML Error", ex.Message);
                return null; 
            }

        }

I get an error Pref is an unexpected token. The expected token is
=
Line 2, position 20.
Was this page helpful?