Search code examples
c#xmlunity-game-enginexmldocument

I can not add a node to the XML file within the right element


When I save a new Question element, I need it to be inside the questions element, which in turn is inside the QuestionCollection, but the way I'm saving the new elements are outside the questions and are not read later. How XML is getting: (ABA IS NEW ELEMENT)

<?xml version="1.0" encoding="UTF-8"?>
<QuestionCollection>
    <Question Titulo="ABA">
      <Enunciado>ABB</Enunciado>
      <Resposta1>ABC</Resposta1>
      <Resposta2>ABD</Resposta2>
      <Resposta3>ABE</Resposta3>
      <Resposta4>ABF</Resposta4>
      <RespostaC>ABC</RespostaC>
    </Question>
  <Questions>
    <START>
    </START>
    <Question Titulo="AAA">
      <Enunciado>AAB</Enunciado>
      <Resposta1>AAC</Resposta1>
      <Resposta2>AAD</Resposta2>
      <Resposta3>AAE</Resposta3>
      <Resposta4>AAF</Resposta4>
      <RespostaC>AAF</RespostaC>
    </Question>
  </Questions>
</QuestionCollection>

How should I stay:

<?xml version="1.0" encoding="UTF-8"?>
<QuestionCollection>
  <Questions>
    <START>
    </START>
    <Question Titulo="AAA">
      <Enunciado>AAB</Enunciado>
      <Resposta1>AAC</Resposta1>
      <Resposta2>AAD</Resposta2>
      <Resposta3>AAE</Resposta3>
      <Resposta4>AAF</Resposta4>
      <RespostaC>AAF</RespostaC>
    </Question>
    <Question Titulo="ABA">
      <Enunciado>ABB</Enunciado>
      <Resposta1>ABC</Resposta1>
      <Resposta2>ABD</Resposta2>
      <Resposta3>ABE</Resposta3>
      <Resposta4>ABF</Resposta4>
      <RespostaC>ABC</RespostaC>
    </Question>  
</Questions>
</QuestionCollection>

Part of Code

XmlDocument doc = new XmlDocument ();
doc.Load ("Assets/Resources/Questions.xml");

XmlNode root = doc.DocumentElement;

XmlElement q = doc.CreateElement ("Question");
q.InnerText = Question;

XmlNode qa = doc.SelectSingleNode ("QuestionCollection/Questions/START");

root.InsertAfter(q,qa);

doc.Save ("Assets/Resources/Questions.xml");
Instance.CloseWindow ();

ERROR: ArgumentException: The reference node is not a child of this node.


Solution

  • @Marshall Tigerus is correct, but there's more;

    Change this:

    XmlElement q = doc.CreateElement("Question");
    q.InnerText = Question;
    
    XmlNode qa = doc.SelectSingleNode("QuestionCollection/Questions");
    XmlNode start = qa.SelectSingleNode("START");
    
    qa.InsertAfter(q,start);