C# MVC 读取XML,写入XML节点,移除XML节点
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Xml.Linq;
using Newtonsoft.Json;
using Sds.Application;
namespace Sds.WebApp.ApiControllers
{
[CustomAuthorizeApi]
public class XmlController : SdsApiController
{
private readonly string path = HttpContext.Current.Server.MapPath("~/sdsWebConfig.xml");
private readonly XDocument document;
public XmlController()
{
if (System.IO.File.Exists(path))
{
document = XDocument.Load(path);
}
else
{
document = new XDocument();
XElement root = new XElement("SDSWEB");
root.Save(path);
document = XDocument.Load(path);
}
}
[HttpPost]
public OperationOutpu SetConfig(XmlModel input)
{
try
{
XElement root = document.Root;
XElement xml = root.Element(input.TagName);
if (xml == null)
{
xml = new XElement(input.TagName);
xml.Value = JsonConvert.SerializeObject(input.Value);
root.Add(xml);
}
else
{
xml.Value = JsonConvert.SerializeObject(input.Value);
}
root.Save(path);
return new OperationOutpu { Status = true };
}
catch (Exception e)
{
return new OperationOutpu { Status = false, Msg = e.Message };
throw new Exception(e.Message);
}
}
[HttpGet]
public object GetConfig(string tagName)
{
XElement root = document.Root;
XElement xml = root.Element(tagName);
if (xml != null)
return JsonConvert.DeserializeObject(xml.Value);
else
return null;
}
[HttpPost]
public OperationOutpu RemoveConfig(string tagName)
{
try
{
XElement root = document.Root;
XElement xml = root.Element(tagName);
xml.Remove();
root.Save(path);
return new OperationOutpu { Status = true };
}
catch (Exception e)
{
return new OperationOutpu { Status = false, Msg = e.Message };
throw new Exception(e.Message);
}
}
}
public class XmlModel
{
public string TagName { get; set; }
public object Value { get; set; }
}
}