我最近一直在尝试使用C#.NET 3.5将某些内容添加到XML数组中,这就是我所拥有的:
public void WriteToXML(string IP)
{
XDocument xmldoc = XDocument.Load("Plugins/SimpleIPBan/SimpleIPBan.configuration.xml");
XElement parentXElement = xmldoc.XPathSelectElement("BannedIPs");
XElement newXElement = new XElement("BannedIP", $"{IP}");
parentXElement.Add(newXElement);
xmldoc.Save("Plugins/SimpleIPBan/SimpleIPBan.configuration.xml");
}
我希望此代码对 SimpleIPBan.configuration.xml 文件执行以下操作:
<?xml version="1.0" encoding="utf-8"?>
<ConfigurationSimpleIPBan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<KickOnIPBan>false</KickOnIPBan>
<KickReason>IP is blacklisted.</KickReason>
<BannedIPs>
<BannedIP>00.000.000.000</BannedIP>
<BannedIP>NewArrayItemHere</BannedIP>
</BannedIPs>
</ConfigurationSimpleIPBan>
但是,当我执行该操作时,出现以下错误:
System.InvalidProgramException: Invalid IL code in System.Xml.Linq.XDocument:Load (string): IL_0000: ret
at SimpleIPBan.SimpleIPBan.WriteToXML (System.String IP) [0x00000] in <filename unknown>:0
at SimpleIPBan.SimpleIPBan.AddIP (IRocketPlayer Caller, System.String IP) [0x00000] in <filename unknown>:0
我已经搜索了此错误,我看到有人提到未定义局部变量的事实,但是我看不到我要去哪里。任何帮助表示赞赏。
答案 0 :(得分:0)
尝试以下操作:
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);
}
这里是完整的工作代码
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);
}
}
}