C#将节点追加到现有的xml文件中

本文关键字:xml 文件 节点 追加 | 更新日期: 2023-09-27 18:21:41

我正在使用XMLWriter创建聊天xml。应通过将收到的消息附加到现有聊天文件中来更新此文件。例如,在下面的xml文件中,我想在msg_id=5的节点之后添加一个新的消息节点。我的问题是,我得到的代码创建了一个新xml文件。请提供建议。

我的XML文件

<?xml version="1.0" encoding="utf-8"?>
<client>
    <name>client_name</name>
    <url>client_name.myapp.com</url>
    <ver>1</ver>
    <conversation>
        <sender_id>5</sender_id>
        <fname>First</fname>
        <mname>Middle</mname>
        <lname>Last</lname>
        <last_seen>l, d-M-y H:i:s T</last_seen>
        <messages>
            <message>
                <msg_id>1</msg_id>
                <recepient_id />
                <message>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</message>
            </message>
            <message>
                <msg_id>2</msg_id>
                <recepient_id />
                <message>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</message>
            </message>
            <message>
                <msg_id>3</msg_id>
                <recepient_id />
                <message>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</message>
            </message>
            <message>
                <msg_id>4</msg_id>
                <recepient_id />
                <message>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</message>
            </message>
            <message>
                <msg_id>5</msg_id>
                <recepient_id />
                <message>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</message>
            </message>
        </messages>
    </conversation>
</client>

我的代码

chat = JsonConvert.DeserializeObject<Chat>(json_data);
            for (int conversations_count = 0; conversations_count < chat.conversations.Count; conversations_count++) // Loop through List with for
            {
                var conversation = chat.conversations[conversations_count];
                var conversation_file_name = conversation.fname + " " + conversation.mname + " " + conversation.lname;
                var messages = conversation.messages;
                if (File.Exists(conversation_file_name))
                {
                using (XmlWriter writer = XmlWriter.Create(conversation_file_name+".xml"))
                    {
                        writer.WriteStartDocument();
                        writer.WriteStartElement("client");
                        writer.WriteElementString("name", "client_name");
                        writer.WriteElementString("url", "client_name.myapp.com");
                        writer.WriteElementString("ver", "1.0");
                        writer.WriteStartElement("conversation");
                        writer.WriteElementString("sender_id", conversation.sender_id.ToString());
                        writer.WriteElementString("fname", conversation.fname.ToString());
                        writer.WriteElementString("mname", conversation.mname.ToString());
                        writer.WriteElementString("lname", conversation.lname.ToString());
                        writer.WriteElementString("last_seen", conversation.last_seen.ToString());
                        writer.WriteStartElement("messages");
                        for (int messages_count = 0; messages_count < messages.Count; messages_count++) // Loop through List with for
                        {
                            writer.WriteStartElement("message");
                            writer.WriteElementString("msg_id", messages[messages_count].msg_id.ToString());                           
                            writer.WriteElementString("recepient_id", messages[messages_count].recepient_id.ToString());
                            writer.WriteElementString("message", messages[messages_count].message.ToString());
                            writer.WriteEndElement();
                        }
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                        writer.WriteEndDocument();
                    }
                }               
            }

C#将节点追加到现有的xml文件中

我建议使用更简单的XML API,例如,使用XmlDocument:

var doc = new XmlDocument();
doc.Load(conversation_file_name);
var messagesNode = doc.DocumentElement
                      .SelectSingleNode("/client/conversation/messages");
var lastMessageId = messagesNode.SelectSingleNode("./message[last()]/msg_id");
var id = lastMessageId != null ? int.Parse(lastMessageId.InnerText.Trim()) : 0;
for (int messages_count = 0; messages_count < messages.Count; messages_count++) // Loop through List with for
{
    //create nodes to be added to existing XML
    var newMessage = doc.CreateElement("message");
    var newId = doc.CreateElement("msg_id");
    var newRecepient = doc.CreateElement("recepient_id");
    var newMessageContent = doc.CreateElement("message");
    //set new nodes content
    newId.InnerText = messages[messages_count].msg_id.ToString();
    newRecepient.InnerText = messages[messages_count].recepient_id.ToString();
    newMessageContent.InnerText = messages[messages_count].message.ToString();
    //append each node to desired parent node
    newMessage.AppendChild(newId);
    newMessage.AppendChild(newRecepient);
    newMessage.AppendChild(newMessageContent);
    messagesNode.AppendChild(newMessage);
}
doc.Save(conversation_file_name);