Delete node/group of elements in XML file

Question

It's Solve

-The code below works, however for Question that had already been saved in the XML file does not work, only for those that are saved during the execution of the application.-

The problem is that the Title string is not being sent.

TitleTxtD.onClick.AddListener(delegate(){ Instance.DeleteXML(strTitle); });

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>

Show source
| c#   | xml   | unity3d   2016-11-20 16:11 2 Answers

Answers to Delete node/group of elements in XML file ( 2 )

  1. 2016-11-20 16:11
    XmlElement el = (XmlElement)doc.SelectSingleNode("/QuestionCollection/Questions/Question[@titulo='"+titulo+"']");
    if(el != null) { el.ParentNode.RemoveChild(el); }
    
  2. 2016-11-20 17:11

    You might as well consider using a newer XML API, providing you with clearer syntax:

    var titulo = "bvc";
    XDocument doc = XDocument.Load(your_path); 
    
    var el2remove = doc.XPathSelectElement($"/QuestionCollection/Questions/Question[@Titulo='{titulo}']");
    el2remove.Remove();
    

Leave a reply to - Delete node/group of elements in XML file

◀ Go back