有没有办法在不使用 XDocument 的情况下将新的 xml 数据附加到 xml 文件中已经存在的 xml?

Is there a way to append new xml data to already existing xml in an xml file without using XDocument?

通常,我将日志消息写入 xml 文件。我用 LinqXDocument.

当 xml 日志变大时,我通常 UI 没有响应,因此我正在寻找实现相同结果的替代方法。

以下是我如何使用 Linq.

登录到 xml 文件的摘录
// Create the xml file if it does not exist
if (!File.Exists(_filePath))
{
    _xmlDocument = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
        new XElement("Logs"));

    _xmlDocument.Save(_filePath);
}

// Load the xml file
_xmlDocument = XDocument.Load(_filePath);

// Add new log to the logs
_xmlDocument?.Element("Logs")?
    .AddFirst(new XElement($"{logLevel.ToString()}",
              new XAttribute("Date", DateTime.Now.ToString("g")),
              new XAttribute("Filepath", $"{values?[1]}"),
                  new XElement("Exception", new XAttribute("EventId", eventId), exception.Source),
                               new XElement("Message",
                               new XAttribute("Origin", $"{values?[0]}"),
                               new XAttribute("LineNumber", $"{values?[2]}"),
                               $"{values?[3]}")
                               )
              );

            // Save the document
            _xmlDocument.Save(_filePath);

您可以尝试将Xml文件当作数据表来使用,插入一条记录,然后重新写入文件。 例如:

        DataSet oDataset = new DataSet();
        oDataset.ReadXml(yourfile);
        DataTable dt = oDataset.Tables["yourtable"];
        //Insert a record
        oDataset.WriteXml(yourfile);

一种技术是像这样维护日志文件

<log-entry.../>
<log-entry.../>
<log-entry.../>

没有封闭的包装器元素。这意味着您可以使用普通的文件附加方法附加到它。然后,当您想将其读取为 XML 时,将其作为来自另一个文件的外部实体引用:

<!DOCTYPE log [
<!ENTITY e SYSTEM "logdata.xml">
]>
<log>&e;</log>

当您读取文件时,您仍然会承担解析的全部费用,但您现在可以直接附加到它,而且成本较低。

当然缺点是现在的安全人员对外部实体很偏执。