I have an xml file that looks like this:

<dialog> <name>5</name> <onEvent type="quest" status="completed">2</onEvent> <disposable>true</disposable> <replic> <character>frost</character> <message>Вот так, просыпайтесь, мисс Хоуп.</message> </replic> <replic> <character>betty_hope</character> <message>Я ничего не понимаю. Доктор Мороу жив? Он с кем-то говорил...</message> </replic> <replic> <character>frost</character> <message>Вам почудилось, мисс. Доктор мертв. А у вас был шок.</message> </replic> </dialog> 

I'm trying to make an editor in C # that would allow me to add and edit dialogs in this file. Now my dialogs are stored in an array of Phrase objects. The class itself consists of 2 elements of the string type:

  1. one for character name
  2. another for replica.

Using Linq to XML add all elements from an array to an XML file.

    2 answers 2

    Changed the way the task XElement, just the same through .Add and got what he wanted.

     XElement onEvent = new XElement("onEvent",task_name.Text.ToString()); onEvent.Add(new XAttribute("type", EventType.Text.ToString())); onEvent.Add(new XAttribute("status", EventStatus.Text.ToString())); dialog.Add(onEvent); XElement name = new XElement("name", Dialog_name.Text.ToString()); dialog.Add(name); XElement dissposable = new XElement("dissposable", testT); dialog.Add(dissposable); foreach (Phrase element in EndArray) { XElement replic = new XElement("replic"); XElement character = new XElement("character", element.get_char(element)); replic.Add(character); XElement message = new XElement("message", element.get_phrase(element)); replic.Add(message); dialog.Add(replic); } 

      Add - no way. LINQ to XML is a functional thing. But you can convert the dialog into an XDocument by doing something like this:

       var name = new XElement("name", dialog.Name); var disposable = new XElement("disposable", dialog.Disposable); var replics = dialog.Replics.Select(r => new XElement("replic", new XElement("character", r.Character), new XElement("message", r.Message) ) ); var documentContent = new [] { name, disposable } .Concat(replics) .ToArray(); var document = new XDocument( new XElement("dialog", documentContent) ); 
      • Yah? And the Add method doesn't seem to exist, does it? - Pavel Mayorov