Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using XML files to store data in C#

I'm basically looking for someone to point me in the right direction on this. I read through some of the Microsoft documentation, but that wasn't very helpful. This is my first attempt at working with XML.

I'm writing an application that needs to store a list of known users and a list of aliases created by each of those users. I've figured out how to have my lists serialized and stored to XML files when the application closes and have it retrieve those when the application opens again, but I don't want to keep the list of users and aliases in memory.

In order for this to work, I need to have the ability to search, edit, and append to the XML file during run time.

The XML structure I envision is something like:

<UserRecord>
    <User>Username-1</User>
    <AliasRecord>
        <Alias>Alias-1</Alias>
        <Number>6135551234</Number>
    </AliasRecord>
    <AliasRecord>
        <Alias>Alias-2</Alias>
        <Number>6131238888</Number>
    </AliasRecord>
</UserRecord>

Each user would only have one username but could have multiple aliases. I need to have the ability to add users, add aliases to a new or existing user, and change existing aliases. Usernames would never change, but an entire User record could be deleted.

So far, the only XML I've done in C# uses serialization but I don't think that approach will work for the above.

    private void WriteXML()
    {
        try
        {
            System.Xml.Serialization.XmlSerializer XMLwriter = new System.Xml.Serialization.XmlSerializer(typeof(MessageRecord));

            System.IO.StreamWriter XMLfile = new System.IO.StreamWriter("Saved MessageRecords.xml");
            foreach (MessageRecord mr in OutgoingMessages)
            {
                XMLwriter.Serialize(XMLfile, mr);
            }
            XMLfile.Close();
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }
    }
like image 863
PAUL DUFRESNE Avatar asked Aug 18 '14 16:08

PAUL DUFRESNE


People also ask

Can XML be used to store data?

Using XML to Store DataYou can use XML to store data in files or in databases. You can write applications to store and retrieve information from the store and use generic applications to display the data.

Why XML is used for storing data?

XML data is stored in plain text format. This provides a software- and hardware-independent way of storing data. This makes it much easier to create data that can be shared by different applications.

How do you store XML files?

The process of storing an XML document has three steps. Obtain an XML document handler by compiling XML document into internal DOM representation, using the stored procedure sp_xml_preparedocument . Construct a schema by associating schema fields with atomic XML elements.

Can XML transport data?

XML is Often a Complement to HTML In many HTML applications, XML is used to store or transport data, while HTML is used to format and display the same data.


1 Answers

Create two classes to represent UserRecord and AliasRecord.

public class UserRecord
{
    public string User { get; set; }
    public List<AliasRecord> AliasRecords { get; set; }
}

public class AliasRecord
{
    public string Alias { get; set; }
    public string Number { get; set; }
}

Populate them like this:

 var userRecord = new UserRecord 
 { 
     User = "UserName1", 
     AliasRecord = new List<AliasRecord> {
        new AliasRecord { Alias = "Alias1", Number = "12345678" }, 
        new AliasRecord { Alias = "Alias2", Number = "23456789" }
     }
 };

And use this code to serialize/deserialize it:

public static class XmlHelper
{
    public static bool NewLineOnAttributes { get; set; }
    /// <summary>
    /// Serializes an object to an XML string, using the specified namespaces.
    /// </summary>
    public static string ToXml(object obj, XmlSerializerNamespaces ns)
    {
        Type T = obj.GetType();

        var xs = new XmlSerializer(T);
        var ws = new XmlWriterSettings { Indent = true, NewLineOnAttributes = NewLineOnAttributes, OmitXmlDeclaration = true };

        var sb = new StringBuilder();
        using (XmlWriter writer = XmlWriter.Create(sb, ws))
        {
            xs.Serialize(writer, obj, ns);
        }
        return sb.ToString();
    }

    /// <summary>
    /// Serializes an object to an XML string.
    /// </summary>
    public static string ToXml(object obj)
    {
        var ns = new XmlSerializerNamespaces();
        ns.Add("", "");
        return ToXml(obj, ns);
    }

    /// <summary>
    /// Deserializes an object from an XML string.
    /// </summary>
    public static T FromXml<T>(string xml)
    {
        XmlSerializer xs = new XmlSerializer(typeof(T));
        using (StringReader sr = new StringReader(xml))
        {
            return (T)xs.Deserialize(sr);
        }
    }

    /// <summary>
    /// Deserializes an object from an XML string, using the specified type name.
    /// </summary>
    public static object FromXml(string xml, string typeName)
    {
        Type T = Type.GetType(typeName);
        XmlSerializer xs = new XmlSerializer(T);
        using (StringReader sr = new StringReader(xml))
        {
            return xs.Deserialize(sr);
        }
    }

    /// <summary>
    /// Serializes an object to an XML file.
    /// </summary>
    public static void ToXmlFile(Object obj, string filePath)
    {
        var xs = new XmlSerializer(obj.GetType());
        var ns = new XmlSerializerNamespaces();
        var ws = new XmlWriterSettings { Indent = true, NewLineOnAttributes = NewLineOnAttributes, OmitXmlDeclaration = true };
        ns.Add("", "");

        using (XmlWriter writer = XmlWriter.Create(filePath, ws))
        {
            xs.Serialize(writer, obj);
        }
    }

    /// <summary>
    /// Deserializes an object from an XML file.
    /// </summary>
    public static T FromXmlFile<T>(string filePath)
    {
        StreamReader sr = new StreamReader(filePath);
        try
        {
            var result = FromXml<T>(sr.ReadToEnd());
            return result;
        }
        catch (Exception e)
        {
            throw new Exception("There was an error attempting to read the file " + filePath + "\n\n" + e.InnerException.Message);
        }
        finally
        {
            sr.Close();
        }
    }
}

Example usage:

var result = XmlHelper.ToXml(userRecord);

Result:

<UserRecord>
    <User>Username1</User>
    <AliasRecords>
        <AliasRecord>
            <Alias>Alias1</Alias>
            <Number>12345678</Number>
        </AliasRecord>
        <AliasRecord>
            <Alias>Alias2</Alias>
            <Number>23456789</Number>
        </AliasRecord>
    </AliasRecords>
</UserRecord>
like image 131
Robert Harvey Avatar answered Sep 23 '22 03:09

Robert Harvey