【问题标题】:Appending an existing XML file附加现有的 XML 文件
【发布时间】:2013-09-09 23:24:12
【问题描述】:

我有一个现有的 XML 文件,我想在不更改格式的情况下附加它。现有文件如下所示:

<Clients>
  <User username="farstucker">
    <UserID>1</UserID>
    <DOB />
    <FirstName>Steve</FirstName>
    <LastName>Lawrence</LastName>
    <Location>NYC</Location>
  </User>
</Clients>

如何使用这种格式添加其他用户?我现有的代码是:

        string fileLocation = "clients.xml";

        XmlTextWriter writer;

        if (!File.Exists(fileLocation))
        {
            writer = new XmlTextWriter(fileLocation, null);
            writer.WriteStartDocument();

            // Write the Root Element
            writer.WriteStartElement("Clients");

            // End Element and Close
            writer.WriteEndElement();
            writer.Close();
        }
// Append new data here

我考虑过使用 XmlDocument Fragment 来附加数据,但我不确定是否可以在不弄乱文件的情况下保持现有格式(和空标签)。

非常感谢您提供的任何建议。

编辑我已更改代码以读取原始 XML,但文件不断被覆盖。

【问题讨论】:

  • 不要使用new XmlTextWriter()。自 .NET 2.0 以来,这已被弃用。请改用XmlWriter.Create()

标签: c# xml


【解决方案1】:

您应该使用 XmlDocument 类来加载整个文件,在内存中对其进行修改,然后将内容写回以替换原始文件。不用担心,它不会弄乱您的标记,您甚至可以使用 PreserveWhitespace 属性 (http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.preservewhitespace.aspx) 要求它在原始文档中保留不重要的空白。

【讨论】:

  • 我同意 kicsit 所说的,除了他说“XmlDocument”的部分,你想使用 XDocument 和 Linq to XML,因为它更好更容易使用。有一个静态加载方法可以从文件中读取文档和等效的保存。
  • 我相信大多数问题都没有说明他们使用的是什么版本的 .NET。 LINQ 在 2.0 或更早版本中不存在。
【解决方案2】:

你可以试试这样的……

        string fileLocation = "clients.xml";

        if (!File.Exists(fileLocation))
        {
            XmlTextWriter writer = new XmlTextWriter( fileLocation, null );
            writer.WriteStartElement( "Clients" );
            writer.WriteEndElement();
            writer.Close();
        }

        // Load existing clients and add new 
        XElement xml = XElement.Load(fileLocation);
            xml.Add(new XElement("User",
            new XAttribute("username", loginName),
            new XElement("DOB", dob),
            new XElement("FirstName", firstName),
            new XElement("LastName", lastName),
            new XElement("Location", location)));
        xml.Save(fileLocation);

这应该让您开始,只需将变量替换为您正在使用的任何内容,并且不要忘记添加 System.Xml.Linq 命名空间。

如果您仍然遇到问题,请返回这里并帮助您解决问题。

【讨论】:

    【解决方案3】:

    如果你想使用序列化(意味着你有一个数据对象想要序列化为 XML 并附加到现有的 XML 文件)你可以使用这个通用方法SerializeAppend&lt;T&gt;。它完全符合您的需要。我还为任何可能受益的人添加了另外两种方法

    public static void Serialize<T>(T obj, string path)
    {
        var writer = new XmlSerializer(typeof(T));
    
        using (var file = new StreamWriter(path))
        {
            writer.Serialize(file, obj);
        }
    }
    
    
    public static T Deserialize<T>(string path)
    {
        var reader = new XmlSerializer(typeof(T));
        using (var stream = new StreamReader(path))
        {
            return (T)reader.Deserialize(stream);
        }
    
    }
    
    public static void SerializeAppend<T>(T obj, string path)
    {
        var writer = new XmlSerializer(typeof(T));
    
        FileStream file = File.Open(path, FileMode.Append, FileAccess.Write);
    
        writer.Serialize(file, obj);
    
        file.Close();
    }
    

    【讨论】:

    • 这样,它会再次附加相同的命名空间。它不会附加到最后一个子节点,但只会附加到文档末尾
    猜你喜欢
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    相关资源
    最近更新 更多