I'm Trying to Delete a node from XML with C#, but for some reason I can't.
What I doing wrong?
The code runs well, respond with true, but the XML don't change and the node is not eliminated.
This is my code to Delete:
internal static bool DeleteCamera(string name)
{
XmlDocument xml = new XmlDocument();
xml.Load("xmlpath.xml");
XmlNode toDelete = xml.SelectSingleNode("//Camera[@Name='" + name + "']");
if (toDelete == null)
{
return false;
}
else
{
toDelete.ParentNode.RemoveChild(toDelete);
xml.Save("xmlpath.xml");
return true;
}
}
This is my XML result with WCF service:
<Cameras>
<Camera Name="Camara1" Url="Camara1" Width="600" Height="800" />
<Camera Name="Camara2" Url="Camara2" Width="600" Height="800" />
</Cameras>
Thank you guys, the problem was the containing apostrophe (?) before and after name string.
XmlNode toDelete = xml.SelectSingleNode("//Camera[@Name='" +name+ "']");
But I don't know why I need to restart the service to see the changes if I have a Method to load the xml file.
Use xml linq. The name in xml is "Camara1" not "Camera1".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
string removeName = "Camara1";
XElement camera = doc.Descendants().Where(x => (x.Name.LocalName == "Camera") && ((string)x.Attribute("Name") == removeName)).FirstOrDefault();
camera.Remove();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.