使用XML文件将数据存储在C# [英] Using XML files to store data in C#

查看:152
本文介绍了使用XML文件将数据存储在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上是在寻找一个人,指出我在这方面的正确方向。我阅读了一些Microsoft文档,但是这不是非常有帮助。这是我第一次尝试使用XML。



我正在编写一个应用程序,需要存储一个已知用户列表和一个别名列表用户。我想出了如何让我的列表序列化和存储到XML文件,当应用程序关闭时,它会检索那些当应用程序再次打开,但我不想保留用户和别名在内存中的列表。 / p>

为了使其正常工作,我需要能够在运行时搜索,编辑和附加到XML文件。



我想象的XML结构是:

 < UserRecord> 
< User>用户名-1< / User>
< AliasRecord>
< Alias>别名-1< / Alias>
< Number> 6135551234< / Number>
< / AliasRecord>
< AliasRecord>
< Alias>别名-2< / Alias>
< Number> 6131238888< / Number>
< / AliasRecord>
< / UserRecord>

每个用户只能有一个用户名,但可以有多个别名。我需要能够添加用户,向新用户或现有用户添加别名,并更改现有别名。用户名不会改变,可以删除整个用户记录。



到目前为止,我在C#中做的唯一的XML使用序列化,但我不认为该方法将为上述工作。

  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);
}
}


解决方案

两个类代表 UserRecord AliasRecord

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

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

如下填充:

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

并使用此代码序列化/反序列化:

  public static class XmlHelper 
{
public static bool NewLineOnAttributes {get;组; }
///< summary>
///使用指定的命名空间将对象序列化为XML字符串。
///< / 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>
///将对象序列化为XML字符串。
///< / summary>
public static string ToXml(object obj)
{
var ns = new XmlSerializerNamespaces();
ns.Add(,);
return ToXml(obj,ns);
}

///< summary>
///从XML字符串中反序列化对象。
///< / 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>
///使用指定的类型名称对XML字符串中的对象进行反序列化。
///< / 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>
///将对象序列化为XML文件。
///< / 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(,);

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

///< summary>
///对XML文件中的对象进行反序列化。
///< / 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(尝试读取文件时出现错误+ filePath +\\\
\\\
+ e.InnerException.Message);
}
finally
{
sr.Close();
}
}
}

用法示例:

  var result = XmlHelper.ToXml(userRecord); 

结果:

 code>< UserRecord> 
< User>用户名1< / User>
< AliasRecords>
< AliasRecord>
< Alias> Alias1< / Alias>
< Number> 12345678< / Number>
< / AliasRecord>
< AliasRecord>
< Alias> Alias2< / Alias>
< Number> 23456789< / Number>
< / AliasRecord>
< / AliasRecords>
< / UserRecord>


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, bu 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);
        }
    }

解决方案

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>

这篇关于使用XML文件将数据存储在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆