Getting an error when trying to append to an XML Array in C# .NET

后端 未结 1 1852
悲&欢浪女
悲&欢浪女 2021-01-26 04:58

I\'ve recently been trying to add something to an Array in XML using C# .NET 3.5, here is what I have:

    public void WriteToXML(string IP)
    {
        XDocum         


        
相关标签:
1条回答
  • 2021-01-26 05:55

    Try following :

        public void WriteToXML(string filename, string IP)
        {
            XDocument xmldoc = XDocument.Load(filename);
            XElement bannedIPs = xmldoc.Descendants("BannedIPs").FirstOrDefault();
            XElement newXElement = new XElement("BannedIP", IP);
            bannedIPs.Add(newXElement);
            xmldoc.Save(filename);
        }    
    

    Here is full working code

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    
    namespace TP3
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XDocument xmldoc = XDocument.Load(FILENAME);
                XElement bannedIPs = xmldoc.Descendants("BannedIPs").FirstOrDefault();
    
                string IP = "NewArrayItemHere";
                XElement newXElement = new XElement("BannedIP", IP);
                bannedIPs.Add(newXElement);
                xmldoc.Save(FILENAME);
            }
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题