LuizaoGT LuizaoGT - 15 days ago 5
C# Question

Delete node/group of elements in XML file

I need to create a function that deletes Nodes from an XML file. I tried a code (below) but it does not work, any ideas how to help me? I need to go in the XML file to find and delete the Question with the desired Title, I do not know if it is automatic, but I need to delete the Elements that are inside the Question together.

public void DeleteXML(string titulo){
XmlDocument doc = new XmlDocument ();
doc.Load ("Assets/Resources/Questions.xml");

XmlNode qa = doc.SelectSingleNode ("QuestionCollection/Questions");
XmlNode q = qa.SelectSingleNode ("Question[@titulo='"+titulo+"']");
q.ParentNode.RemoveChild(q);
doc.Save ("Assets/Resources/Questions.xml");
//XmlNode root = doc.DocumentElement;
Instance.LoadXML ();
}


** The LoadXML function will only update the elements on the screen.

XML FILE:

<?xml version="1.0" encoding="UTF-8"?>
<QuestionCollection>
<Questions>
<Start>
</Start>
<Question Titulo="bvc">
<Enunciado>xcv</Enunciado>
<Resposta1>xcv</Resposta1>
<Resposta2>xcv</Resposta2>
<Resposta3>xcv</Resposta3>
<Resposta4>vxcv</Resposta4>
<RespostaC>xcv</RespostaC>
</Question>
</Questions>
</QuestionCollection>

Answer
XmlElement el = (XmlElement)doc.SelectSingleNode("/QuestionCollection/Questions/Question[@titulo='"+titulo+"']");
if(el != null) { el.ParentNode.RemoveChild(el); }
Comments