Home > Software engineering >  How can i write in an Linq to Xml new Element an dynamic value?
How can i write in an Linq to Xml new Element an dynamic value?

Time:03-09

everyone i have an question on how to write the number of my Enumerable.Range inside an new XElement i create. I want my code to put for example the current value of "i" inside the Element just like i'm used to do it with {0} but it doesn't work. I've put some code snipped out of my programm that should explain what my problem is.

  public static void PLCreate() {
        int zahler = 0;
        XDocument xmlDocument = new XDocument( 
            new XDeclaration("1.0", "utf-8", "yes"),
                new XElement("Document",
    Enumerable.Range(0, 10).Select(i => new XElement("Hmi.Tag.Tag", new XAttribute("ID", zahler = zahler   1), new XAttribute("CompositionName", "Tags"),
         new XElement("Name", "HMI_Messages_Modul_Axis_Faults{Here is where i should change}_R"), //Here is where i should change
         new XElement("Name", "HMI_Messages.Modul_Axis_Faults[Here inside also].R"))));}

CodePudding user response:

In Interpolated Strings, the dollar sign ($) is used to tell the C# compiler that the string following it is to be interpreted as an Interpolated String. The curly braces encapsulate the values (of the variables) to include in the text.Source

And if you want that the string contains an curly brace, than you have to put 3 of them. Like in my example below.

public static void PLCreate() {
        int zahler = 0;
        XDocument xmlDocument = new XDocument( 
            new XDeclaration("1.0", "utf-8", "yes"),
                new XElement("Document",
    Enumerable.Range(0, 10).Select(i => new XElement("Hmi.Tag.Tag", new XAttribute("ID", zahler = zahler   1), new XAttribute("CompositionName", "Tags"),
         new XElement("Name", $"HMI_Messages_Modul_Axis_Faults{{{Here is where i should change}}}_R"), //Here is where i should change
         new XElement("Name", $"HMI_Messages.Modul_Axis_Faults[Here inside also].R"))));}
  • Related