Création de fichier xml avec linqtoxml

Résolu
Tintin2256 Messages postés 25 Date d'inscription mardi 3 octobre 2017 Statut Membre Dernière intervention 18 septembre 2023 - Modifié le 3 oct. 2017 à 18:28
Whismeril Messages postés 19029 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 26 avril 2024 - 9 oct. 2017 à 17:55
Bonjour,
Je me permets de venir vers vous car je rencontre un petit souci avec Linqtoxml. Je dois créer un fichier xml avec la structure suivante:
<typeLine>
 <emptyCell nbCells="4"></emptyCell>
 <FFBBlock instanceName="C_XV11001_01" typeName="DFB_Valve" additionnalPinNumber="0" enEnO="true" width="12" height="6">
  <objPosition posX="4" posY="3"></objPosition>
  <descriptionFFB execAfter="">
   <inputVariable invertedPin="false" formalParameter="EN"></inputVariable>
   <inputVariable invertedPin="false" formalParameter="ZsOn" effectiveParameter="false"></inputVariable>
   <inputVariable invertedPin="false" formalParameter="ZsOff" effectiveParameter="false"></inputVariable>
   <inputVariable invertedPin="false" formalParameter="IN"></inputVariable>
   <inputVariable invertedPin="false" formalParameter="OUT"></inputVariable>
   <outputVariable invertedPin="false" formalParameter="ENO"></outputVariable>
   <outputVariable invertedPin="false" formalParameter="Xv"></outputVariable>
  </descriptionFFB>
 </FFBBlock>
 <emptyCell nbCells="5"></emptyCell>
</typeLine>
<typeLine>
 <HLink nbCells="4"></HLink>
 <emptyCell nbCells="7"></emptyCell>
</typeLine>

<typeLine>
 <emptyCell nbCells="4"></emptyCell>
 <FFBBlock instanceName="C_XV11001_02" typeName="DFB_Valve" additionnalPinNumber="0" enEnO="true" width="12" height="6">
  <objPosition posX="4" posY="13"></objPosition>
  <descriptionFFB execAfter="">
   <inputVariable invertedPin="false" formalParameter="EN"></inputVariable>
   <inputVariable invertedPin="false" formalParameter="ZsOn" effectiveParameter="false"></inputVariable>
   <inputVariable invertedPin="false" formalParameter="ZsOff" effectiveParameter="false"></inputVariable>
   <inputVariable invertedPin="false" formalParameter="IN"></inputVariable>
   <inputVariable invertedPin="false" formalParameter="OUT"></inputVariable>
   <outputVariable invertedPin="false" formalParameter="ENO"></outputVariable>
   <outputVariable invertedPin="false" formalParameter="Xv"></outputVariable>
  </descriptionFFB>
 </FFBBlock>
 <emptyCell nbCells="5"></emptyCell>
</typeLine>
<typeLine>
 <HLink nbCells="4"></HLink>
 <emptyCell nbCells="7"></emptyCell>
</typeLine>

J'arrive à le générer mais pas comme je veux. J'obtiens ce résultat:

<FFBBlock instanceName="C_XV11031_05" typeName="DFB_Valve" additionnalPinNumber="0" enEnO="true" width="12" height="6">
	<objPosition posX="4" posY="303" />
	<descriptionFFB execAfter="">
	  <inputVariable invertedPin="false" formalParameter="EN" />
	  <inputVariable invertedPin="false" formalParameter="ZsOn" effectiveParameter="false" />
	  <inputVariable invertedPin="false" formalParameter="ZsOff" effectiveParameter="false" />
	  <inputVariable invertedPin="false" formalParameter="IN" />
	  <inputVariable invertedPin="false" formalParameter="OUT" />
	  <outputVariable invertedPin="false" formalParameter="ENO" />
	  <outputVariable invertedPin="false" formalParameter="Xv" />
	</descriptionFFB>
  </FFBBlock>
  <emptyCell nbCells="5" />
</typeLine>
<typeLine>
  <emptyCell nbCells="4" />
  <FFBBlock instanceName="C_EV11031_03" typeName="DFB_Valve" additionnalPinNumber="0" enEnO="true" width="12" height="6">
	<objPosition posX="4" posY="313" />
	<descriptionFFB execAfter="">
	  <inputVariable invertedPin="false" formalParameter="EN" />
	  <inputVariable invertedPin="false" formalParameter="ZsOn" effectiveParameter="false" />
	  <inputVariable invertedPin="false" formalParameter="ZsOff" effectiveParameter="false" />
	  <inputVariable invertedPin="false" formalParameter="IN" />
	  <inputVariable invertedPin="false" formalParameter="OUT" />
	  <outputVariable invertedPin="false" formalParameter="ENO" />
	  <outputVariable invertedPin="false" formalParameter="Xv" />
	</descriptionFFB>
  </FFBBlock>
  <emptyCell nbCells="5" />
</typeLine>
<typeLine>
  <HLink nbCells="4" />
  <emptyCell nbCells="7" />
</typeLine>

Il me manque donc un bout entre deux mais je n'arrive pas à l'introduire.

Voici mon code de base:
//Création du fichier XML source
XDocument XmlDoc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), new XElement("LDExchangeFile", new XElement("fileHeader", new XAttribute("company", "Schneider Automation"), new XAttribute("product", "Unity Pro XL V7.0 - 120823C"), new XAttribute("dateTime", "date_and_time#2017-10-2-15:22:41"), new XAttribute("content", "Fichier source LD"), new XAttribute("DTDVersion", "41")),
	 new XElement("contentHeader", new XAttribute("name", "NVAAP_AP130"), new XAttribute("version", "0.0.102"), new XAttribute("dateTime", "date_and_time#2017-10-2-15:22:41")),
	 new XElement("program", new XElement("identProgram", new XAttribute("name", NomSection), new XAttribute("type", "section"), new XAttribute("task", "MAST"))
		 , new XElement("LDSource", new XAttribute("nbColumns", "11"), new XElement("networkLD", 
				new XElement("typeLine", new XElement("emptyLine", new XAttribute("nbRows", "1"))), 
				new XElement("typeLine", new XElement("contact", new XAttribute("typeContact", "openContact"), new XAttribute("contactVariableName", "false"))
			, new XElement("HLink", new XAttribute("nbCells", "9"))
			, new XElement("coil", new XAttribute("typeCoil", "coil"), new XAttribute("coilVariableName", "XV130011_14.X"))),
				new XElement("typeLine", new XElement("emptyLine", new XAttribute("nbRows", "1"))),
				from p in ListeVannes select new XElement("typeLine", new XElement("emptyCell", new XAttribute("nbCells", "4")), 
		 new XElement("FFBBlock", new XAttribute("instanceName", p.NomVanne), new XAttribute("typeName", "DFB_Valve"), new XAttribute("additionnalPinNumber", "0"), new XAttribute("enEnO", "true"), new XAttribute("width", "12"), new XAttribute("height", "6"),
			new XElement("objPosition", new XAttribute("posX", "4"), new XAttribute("posY", p.PosBloc)),
			new XElement("descriptionFFB", new XAttribute("execAfter", ""),
				new XElement("inputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "EN")),
				new XElement("inputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "ZsOn"), new XAttribute("effectiveParameter", "false")),
				new XElement("inputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "ZsOff"), new XAttribute("effectiveParameter", "false")),
				new XElement("inputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "IN")),
				new XElement("inputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "OUT")),
				new XElement("outputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "ENO")),
				new XElement("outputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "Xv")))),
			  new XElement("emptyCell", new XAttribute("nbCells", "5"))), 
				new XElement("typeLine", new XElement("HLink", new XAttribute("nbCells", "4")), new XElement("emptyCell", new XAttribute("nbCells", "7"))),
				from p in ListeVannes select new XElement("textBox", new XAttribute("width", "11"), new XAttribute("height", "1"),p.Commentaire,
			 new XElement("objPosition", new XAttribute("posX", "0"), new XAttribute("posY", p.PosCom)))))),
	 new XElement("dataBlock", from p in ListeVannes select new XElement("variables", new XAttribute("name", p.NomVanne), new XAttribute("typeName", "DFB_Valve"),
   new XElement("comment", p.Commentaire),
   new XElement("instanceElementDesc", new XAttribute("name", "Gen"),
			new XElement("instanceElementDesc", new XAttribute("name", "Para"),
			new XElement("instanceElementDesc", new XAttribute("name", "Preset_Df_on"), 
			new XElement("value", "t#10s")),
			new XElement("instanceElementDesc", new XAttribute("name", "Preset_Df_off"),
			new XElement("value", "t#10s")),
			new XElement("instanceElementDesc", new XAttribute("name", "Preset_T_exp"),
			new XElement("value", "t#2h"))))))));


//Récupération du nom de la zone pour définir le nom du fichier
XmlDoc.Save(NomDossierDest.Text + @"\SectionVannes.xld");


J'ai une classe à côté d'où j'extrais mes données:
//Déclaration de la classe "Vanne"
public class Vanne
{
    public Vanne() { }
    public Vanne(string NomVanne, string AdresseSortie, string Commentaire, int NumVanne, int PosBloc, int PosCom)
    {
        this.NomVanne = NomVanne;
        this.AdresseSortie = AdresseSortie;
        this.Commentaire = Commentaire;
        this.NumVanne = NumVanne;
        this.PosBloc = PosBloc;
        this.PosCom = PosCom;
    }

    // Auto-implemented properties.
    public string NomVanne { get; set; }
    public string AdresseSortie { get; set; }
    public string Commentaire { get; set; }
    public int NumVanne { get; set; }
    public int PosBloc { get; set; }
    public int PosCom { get; set; }
}

Si quelqu'un avait une idée, ce serait top.

Merci d'avance de votre aide

10 réponses

Whismeril Messages postés 19029 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 26 avril 2024 656
3 oct. 2017 à 20:40
Bonsoir

et d'abord, merci à KX d'avoir corrigé ta coloration syntaxique, c'est plus lisible.
Voir ici la procédure pour bien s'en servir.

0
Whismeril Messages postés 19029 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 26 avril 2024 656
Modifié le 3 oct. 2017 à 20:46
Pour ton "problème" déjà ton fichier modèle contient une ligne vide, ce qui n'est pas conforme au format xml.
Une erreur de copié collé?

Ensuite, le principe de LinqToXml, est de construire un xml à partir de données variables.
Là le code que tu présentes c'est 80% de valeurs en dur dans le code (même la date????).

Ça ne sert à rien de passer par ling pour ça (les parties fixes), prend un fichier modèle et modifie les quelques variables.

Quand j'étais petit, la mer Morte n'était que malade.
George Burns
0
Tintin2256 Messages postés 25 Date d'inscription mardi 3 octobre 2017 Statut Membre Dernière intervention 18 septembre 2023
3 oct. 2017 à 20:58
Salut Whismeril,

Oui c'est une erreur de copié/collé.Sorry

J'avais déjà utilisé cette fonction sous tes conseils il y a quelques années de ça pour un autre sujet et je pensais reprendre le même principe ici. En fait, le modèle "actuel" est assez basique et je compte le faire évoluer dans le futur d'où le choix de cette fonction.

Si je pars sur la base d'un fichier modèle que je modifie, je pourrai le faire comment? Si tu as un petit exemple, je suis preneur car j'ai chercher mais j'arrive pas à trouver ce que je cherche...
0
Whismeril Messages postés 19029 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 26 avril 2024 656
3 oct. 2017 à 21:40
Exemple simple

soit le fichier modele (test.xml)
<?xml version="1.0" encoding="utf-8"?>
<Racine>
  <Balise1>
    <Balise2>
      <ListePersonnes>
        <Personne>
          <Nom Prenom="Alain">Dit</Nom>
          <DateNaisance>1990-06-06T00:00:00</DateNaisance>
        </Personne>
        <Personne>
          <Nom Prenom="Jean">Sort</Nom>
          <DateNaisance>2000-01-01T00:00:00</DateNaisance>
        </Personne>
      </ListePersonnes>
    </Balise2>
  </Balise1>
</Racine>



        private void tintin2256()
        {
            XDocument xdoc = XDocument.Load("test.xml");
            XElement element = xdoc.Descendants("Personne").FirstOrDefault(e => e.Element("Nom").Value == "Dit");
            
            if (element == null)//il n'y a pas d'occurence
                return;

            element.SetElementValue("DateNaisance", DateTime.Now);
            xdoc.Save("testModifie.xml");
        }


Cependant
En fait, le modèle "actuel" est assez basique et je compte le faire évoluer dans le futur d'où le choix de cette fonction.
et le fait que dans ton code, tu itères 2 fois la collection ListeVannes m'interpelle.

Peux tu donner un fichier exemple complet (avec des données non confidentielles) et des valeurs réalistes (mais non confidentielles) dont tu disposes.
Ensuite peux tu préciser ce qui pourrait évoluer à l'avenir?
0
Tintin2256 Messages postés 25 Date d'inscription mardi 3 octobre 2017 Statut Membre Dernière intervention 18 septembre 2023
4 oct. 2017 à 09:49
Salut Whismeril,

Le fichier XML est utilisé dans un logiciel d'automatisme ensuite. La raison d'itérer 2 fois ma collection est que je dois, dans le fichier "source" lui détailler la forme et ensuite le fond (les éléments qui le compose).

Voici le fichier de sortie complet:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<LDExchangeFile>
	<fileHeader company="Schneider Automation" product="Unity Pro XL V7.0 - 120823C" dateTime="date_and_time#2017-10-4-9:31:18" content="Fichier source LD" DTDVersion="41"></fileHeader>
	<contentHeader name="NVAAP_AP124" version="0.0.1" dateTime="date_and_time#2016-7-29-18:48:41"></contentHeader>
	<program>
		<identProgram name="ECH130011_Vannes_ASI" type="section" task="MAST"></identProgram>
		<LDSource nbColumns="11">
			<networkLD>
				<typeLine>
					<emptyLine nbRows="1"></emptyLine>
				</typeLine>
				<typeLine>
					<contact typeContact="openContact" contactVariableName="false"></contact>
					<HLink nbCells="9"></HLink>
					<coil typeCoil="coil" coilVariableName="DFB_Valve_4.X"></coil>
				</typeLine>
				<typeLine>
					<emptyLine nbRows="1"></emptyLine>
				</typeLine>
				<typeLine>
					<emptyCell nbCells="4"></emptyCell>
					<FFBBlock instanceName="DFB_Valve_4" typeName="DFB_Valve" additionnalPinNumber="0" enEnO="true" width="12" height="6">
						<objPosition posX="4" posY="3"></objPosition>
						<descriptionFFB execAfter="">
							<inputVariable invertedPin="false" formalParameter="EN"></inputVariable>
							<inputVariable invertedPin="false" formalParameter="ZsOn" effectiveParameter="false"></inputVariable>
							<inputVariable invertedPin="false" formalParameter="ZsOff" effectiveParameter="false"></inputVariable>
							<inputVariable invertedPin="false" formalParameter="IN"></inputVariable>
							<inputVariable invertedPin="false" formalParameter="OUT"></inputVariable>
							<outputVariable invertedPin="false" formalParameter="ENO"></outputVariable>
							<outputVariable invertedPin="false" formalParameter="Xv"></outputVariable>
						</descriptionFFB>
					</FFBBlock>
					<emptyCell nbCells="5"></emptyCell>
				</typeLine>
				<typeLine>
					<HLink nbCells="4"></HLink>
					<emptyCell nbCells="7"></emptyCell>
				</typeLine>
				<typeLine>
					<emptyLine nbRows="6"></emptyLine>
				</typeLine>
				<typeLine>
					<contact typeContact="openContact" contactVariableName="false"></contact>
					<HLink nbCells="9"></HLink>
					<coil typeCoil="coil" coilVariableName="DFB_Valve_5.X"></coil>
				</typeLine>
				<typeLine>
					<emptyLine nbRows="1"></emptyLine>
				</typeLine>
				<typeLine>
					<emptyCell nbCells="4"></emptyCell>
					<FFBBlock instanceName="DFB_Valve_5" typeName="DFB_Valve" additionnalPinNumber="0" enEnO="true" width="12" height="6">
						<objPosition posX="4" posY="13"></objPosition>
						<descriptionFFB execAfter="">
							<inputVariable invertedPin="false" formalParameter="EN"></inputVariable>
							<inputVariable invertedPin="false" formalParameter="ZsOn" effectiveParameter="false"></inputVariable>
							<inputVariable invertedPin="false" formalParameter="ZsOff" effectiveParameter="false"></inputVariable>
							<inputVariable invertedPin="false" formalParameter="IN"></inputVariable>
							<inputVariable invertedPin="false" formalParameter="OUT"></inputVariable>
							<outputVariable invertedPin="false" formalParameter="ENO"></outputVariable>
							<outputVariable invertedPin="false" formalParameter="Xv"></outputVariable>
						</descriptionFFB>
					</FFBBlock>
					<emptyCell nbCells="5"></emptyCell>
				</typeLine>
				<typeLine>
					<HLink nbCells="4"></HLink>
					<emptyCell nbCells="7"></emptyCell>
				</typeLine>
				<typeLine>
					<emptyLine nbRows="83"></emptyLine>
				</typeLine>
				<textBox width="11" height="1">Gestion de la vanne de bypass Sortie Préchauffeur.<objPosition posX="0" posY="10"></objPosition>
				</textBox>
				<textBox width="11" height="1">Gestion de la vanne de bypass Sortie Préchauffeur.<objPosition posX="0" posY="0"></objPosition>
				</textBox>
			</networkLD>
		</LDSource>
	</program>
	<dataBlock>
		<variables name="DFB_Valve_5" typeName="DFB_Valve"></variables>
		<variables name="DFB_Valve_4" typeName="DFB_Valve"></variables>
	</dataBlock>
</LDExchangeFile>





Comme tu peux le voir dans le fichier, on retrouve 2 fois la "même" structure
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
Whismeril Messages postés 19029 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 26 avril 2024 656
4 oct. 2017 à 20:48
Hum,

et ce genre de trucs
				<typeLine>
					<emptyLine nbRows="1"></emptyLine>
				</typeLine>
				<typeLine>
					<contact typeContact="openContact" contactVariableName="false"></contact>
					<HLink nbCells="9"></HLink>
					<coil typeCoil="coil" coilVariableName="DFB_Valve_4.X"></coil>
				</typeLine>
				<typeLine>
					<emptyLine nbRows="1"></emptyLine>
				</typeLine>

Si ça venait à évoluer ça viendrait d'ou?

Ce que j'imagine est une liste de "line" qui peut être vide et du coup n'a qu'une "row", ou alors contenir un contact ou un hlink un coil ou des cellules vides ou encore un FFBBlock.
Dis moi si je me trompe.

Pour transposer ça de façon totalement "variable", il faut créer des objets qui soit compatibles d'une seule et même liste, c'est gérable avec de l'héritage. Ça va me prendre un peu de temps avant de te proposer une solution fonctionnelle.


D'autre part, est-ce que le "network" peut contenir autre chose que des "line" et des "textbox"?
0
Whismeril Messages postés 19029 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 26 avril 2024 656
6 oct. 2017 à 00:12
Bonsoir

j'ai presque réussi à reproduire ton fichier.
Même l'indentation avec des tabulations et les éléments en ligne fermés par le nom de balise, j'ai agit sur le texte final pour ça.
Tout est paramétrable.
Le code est assez complexe.

Et je bute sur
<textBox width="11" height="1">Gestion de la vanne de bypass Sortie Préchauffeur.<objPosition posX="0" posY="10"></objPosition>

Je pense que la solution la plus simple sera aussi d'agir sur le texte, mais là il est tard.


Je te laisse le code actuel pour que tu me dises si ça te convient.
    class LDExchangeFile
    {
        public LDExchangeFile()
        {
            Compagnie = "Schneider Automation";
            Produit = "Unity Pro XL V7.0 - 120823C";
            DateFileHeader = new DateTime(2017, 10, 4, 9, 31, 18);
            Contenu = "Fichier source LD";
            DTDVersion = "41";
            Nom = "NVAAP_AP124";
            Version = "0.0.1";
            DateContentHeader = new DateTime(2016, 7, 29, 18, 48, 41);
            Prog = new LeProgramme();
        }

        public string Compagnie { get; set; }

        public string Produit { get; set; }

        public string Contenu { get; set; }

        public string DTDVersion { get; set; }

        public DateTime DateFileHeader { get; set; }

        public string Nom { get; set; }

        public string Version { get; set; }

        public DateTime DateContentHeader { get; set; }

        public LeProgramme Prog { get; set; }

        public void AddElementsLignes(params ElementLigne[] Elements)
        {
            Ligne ligne = new Ligne();
            ligne.Elements = Elements.ToList();
            Prog.LdSource.Elements.Add(ligne);
        }

        public void AddTextBox(int Y)
        {
            Prog.LdSource.Elements.Add(new TexteBox { Taille = new Size(0, Y) });
        }

        public void Serialise(string Filename)
        {

            var toto = (from l in Prog.LdSource.Elements.OfType<Ligne>()
                        from fb in l.Elements.OfType<FFBBlock>()
                        select new { Nom = fb.NomInstance, Type = fb.NomType });

            XDocument xdoc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
             new XElement("LDExchangeFile",
                new XElement("fileHeader", new XAttribute("company", Compagnie), new XAttribute("product", Produit), new XAttribute("dateTime", string.Format("date_and_time#{0:yyyy-M-d-H:m:s}", DateFileHeader)), new XAttribute("content", Contenu), new XAttribute("DTDVersion", DTDVersion)),
                new XElement("contentHeader", new XAttribute("name", Nom), new XAttribute("version", Version), new XAttribute("dateTime", string.Format("date_and_time#{0:yyyy-M-d-H:m:s}", DateContentHeader))),
                Prog.Serialize,
                new XElement("dataBlock",
                    from x in toto
                    select new XElement("variables", new XAttribute("name", x.Nom), new XAttribute("typeName", x.Type))
                    )
                    )
                    );

            string texte = xdoc.ToString().Replace("  ", "\t");

            File.WriteAllText(Filename, Regex.Replace(texte, "<([a-z]+)( [^/]+)( />)", "<$1$2></$1>",RegexOptions.IgnoreCase));
        }
    }

    class LeProgramme
    {
        public LeProgramme()
        {
            Nom = "ECH130011_Vannes_ASI";
            Type = "section";
            Tache = "MAST";
            LdSource = new LDSource();
        }

        public string Nom { get; set; }

        public string Type { get; set; }

        public string Tache { get; set; }

        public LDSource LdSource { get; set; }

        public XElement Serialize
        {
            get
            {
                return new XElement("program",
                    new XElement("identProgram", new XAttribute("name", Nom), new XAttribute("type", Type), new XAttribute("task", Tache)),
                    LdSource.Serialize
                    );
            }
        }
    }

    class LDSource
    {
        public LDSource()
        {
            NbreColonnes = 11;
            Elements = new List<NetworkLDElement>();
        }

        public int NbreColonnes { get; set; }

        public List<NetworkLDElement> Elements { get; set; }

        public XElement Serialize
        {
            get
            {
                return new XElement("LDSource", new XAttribute("nbColumns", NbreColonnes),
                    new XElement("networkLD",
                    from e in Elements
                    select e.Serialize
                ));
            }
        }
    }

    abstract class NetworkLDElement
    {
        public abstract  XElement Serialize { get;}
    }

    class Ligne:NetworkLDElement
    {
        public List<ElementLigne> Elements { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("typeLine",
                    from l in Elements
                        select  l.Serialize);
            }
        }
    }

    abstract class ElementLigne
    {
        public abstract XElement Serialize { get; }
    }

    class LeContact:ElementLigne
    {
        public LeContact()
        {
            Type = "openContact";
            Nom = "false";
        }

        public string Type { get; set; }

        public string Nom { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("contact", new XAttribute("typeContact", Type), new XAttribute("contactVariableName", Nom));
            }
        }
    }

    class HLink:ElementLigne
    {
        public HLink()
        {
            NbreCells = 9;
        }

        public int NbreCells { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("HLink", new XAttribute("nbCells", NbreCells));
            }
        }

    }

    class Coil:ElementLigne
    {
        public Coil(string NomVariable)
        {
            Type = "coil";
            this.NomVariable = NomVariable;
        }

        public string Type { get; set; }//si les types sont prédéfinis, on pourrait mettre un enum, ce serait valable plus haut aussi

        public string NomVariable { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("coil", new XAttribute("typeCoil", Type), new XAttribute("coilVariableName",NomVariable));
            }
        }

    }

    class EmptyLine:ElementLigne
    {
        public EmptyLine()
        {
            Nombre = 1;
        }

        public int Nombre { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("emptyLine", new XAttribute("nbRows", Nombre));
            }
        }

    }

    class EmptyCell:ElementLigne
    {
        public EmptyCell()
        {
            Nombre = 4;
        }

        public int Nombre { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("emptyCell", new XAttribute("nbCells", Nombre));
            }
        }

    }

    class FFBBlock:ElementLigne
    {
        public FFBBlock(string InstanceName)
        {
            NomInstance = InstanceName;
            NomType = "DFB_Valve";
            AdditionnalPinNumber = 0;
            EnEnO = true;
            Taille = new Size(12, 6);
            ExecAfter = "";
            Elements = new List<LaVariable>();
        }

        public string NomInstance { get; set; }

        public string NomType { get; set; }

        public int AdditionnalPinNumber { get; set; }

        public bool EnEnO { get; set; }

        public Size Taille { get; set; }

        public Point Position { get; set; }

        public string ExecAfter { get; set; }

        public List<LaVariable> Elements { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("FFBBlock", new XAttribute("instanceName", NomInstance), new XAttribute("typeName", NomType), new XAttribute("additionnalPinNumber", AdditionnalPinNumber), new XAttribute("enEnO", EnEnO), new XAttribute("width", Taille.Width), new XAttribute("height", Taille.Height),
                    new XElement("objPosition", new XAttribute("posX", Position.X), new XAttribute("posY",Position.Y)),
                    new XElement("descriptionFFB", new XAttribute("execAfter", ExecAfter),
                        from e in Elements
                        select e.Serialize
                )
                    );
            }
        }
    }

    class LaVariable
    {
        public LaVariable(bool Input, string FormalParameter, bool? EffectiveParameter = null)
        {
            InvertedPin = false;
            this.FormalParameter = FormalParameter;
            this.EffectiveParameter = EffectiveParameter;
            input = Input;
        }

        bool input;

        public bool InvertedPin { get; set; }

        public string FormalParameter { get; set; }

        public bool? EffectiveParameter { get; set; }

        public XElement Serialize
        {
            get
            {
                return new XElement(input ? "inputVariable" : "outputVariable", new XAttribute("invertedPin", InvertedPin), new XAttribute("formalParameter", FormalParameter), EffectiveParameter == null ? null : new XAttribute("effectiveParameter", EffectiveParameter));
            }
        }
    }

    class TexteBox:NetworkLDElement
    {
        public TexteBox()
        {
            Taille = new Size(11, 1);
            Texte = "Gestion de la vanne de bypass Sortie Préchauffeur.";
            Position = new Point(0, 0);
        }

        public Size Taille { get; set; }

        public string Texte { get; set; }

        public Point Position { get; set; }

        public override XElement Serialize
        {
            get
            {
                return  new XElement("textBox", new XAttribute("width", Taille.Width), new XAttribute("height", Taille.Height), string.Format("{0}<objPosition posX=\"{1}\" posY=\"{2}\"",Texte,Position.X,Position.Y)) ;
            }
        }
    }


Et la construction du fichier
            LDExchangeFile test = new LDExchangeFile();

            test.AddElementsLignes(new EmptyLine());
            test.AddElementsLignes(new LeContact(), new HLink(), new Coil("DFB_Valve_4.X"));
            test.AddElementsLignes(new EmptyLine());
            FFBBlock block = new FFBBlock("DFB_Valve_4");
            block.Position = new Point(4,3);
            block.Elements = new List<LaVariable> { new LaVariable(true,"EN"), new LaVariable(true,"ZsOn", false), new LaVariable(true,"ZsOff", false), new LaVariable(true, "IN"), new LaVariable(true, "OUT"), new LaVariable(false,"ENO"), new LaVariable(false,"Xv") };
            test.AddElementsLignes(new EmptyCell { Nombre = 4 }, block , new EmptyCell { Nombre = 5 });
            test.AddElementsLignes(new HLink { NbreCells = 4 }, new EmptyCell { Nombre = 7 });
            test.AddElementsLignes(new EmptyLine { Nombre = 6 });
            test.AddElementsLignes(new LeContact(), new HLink(), new Coil("DFB_Valve_5.X"));
            test.AddElementsLignes(new EmptyLine());
            FFBBlock block2 = new FFBBlock("DFB_Valve_5");
            block2.Position = new Point(4,13);
            block2.Elements = new List<LaVariable>(block.Elements);
            test.AddElementsLignes(new EmptyCell { Nombre = 4 }, block2 , new EmptyCell { Nombre = 5 });
            test.AddElementsLignes(new HLink { NbreCells = 4 }, new EmptyCell { Nombre = 7 });
            test.AddElementsLignes(new EmptyLine { Nombre = 83 });
            test.AddTextBox(10);
            test.AddTextBox(0);

            test.Serialise("testTintin.xml");


0
Tintin2256 Messages postés 25 Date d'inscription mardi 3 octobre 2017 Statut Membre Dernière intervention 18 septembre 2023
6 oct. 2017 à 08:40
Salut Whismeril,

Merci de ton retour. Je viens de tester ton code et franchement, je suis bluffer. On est pas loin de la solution je pense. Il y a quelques petits "bugs" dans le fichier de sortie mais dans les grandes lignes on est bon.

Dans le début du fichier, je récupère ceci:
<LDExchangeFile>
	<fileHeader company="Schneider Automation" product="Unity Pro XL V7.0 - 120823C" dateTime="date_and_time#2017-10-4-9:31:18" content="Fichier source LD" DTDVersion="41"></fileHeader>
	<contentHeader name="NVAAP_AP124" version="0.0.1" dateTime="date_and_time#2016-7-29-18:48:41"></contentHeader>
	<program>
		<identProgram name="ECH130011_Vannes_ASI" type="section" task="MAST"></identProgram>
		<LDSource nbColumns="11">
			<networkLD>
				<typeLine>
					<emptyLine nbRows="1"></LDSource>
				</typeLine>
				<typeLine>


J'ai un "emptyLine qui s'est transformé en un "LDSource" mais je sais pas trop pourquoi et surtout, pourquoi seulement sur celui là et pas les autres
0
Whismeril Messages postés 19029 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 26 avril 2024 656
6 oct. 2017 à 10:30
Je vais être très occupé ce week-end, j’essayerai de trouver un moment pour finaliser mais sans garantie.

Pour détailler un peu, j’ai écrit une classe par « balise majeure » , c’est à dire que je n’ai pas considéré utile de faire une classe pour l’élément fileHeader, mais qu’à l’inverse dès qu’un schéma se répète (typeLine et ses enfants par exemple) j’ai mis une classe correspondante.

Ensuite, j’ai choisi que chaque classe se serialize elle-même, ça en met un peu partout, mais si un élément contact bugue ça cible de suite le code à corriger.

Certaines classes ont un constructeur avec des valeurs par défaut, d’autres non. J’ai choisi en me basant sur ce fichier, tu pourras ajuster ça en fonction des cas que tu rencontres.


Pour le /emptyline devenu /ldsource, ça vient sans doute de la regex. Pour fermer les balises en ligne comme dans ton exemple et non par la forme simplifiée /> comme la norme le permet, j’ai utilisé une regex.
Si fermer les balises par la forme simplifiée ne gêne pas la suite de tes processus, on pourra sortir ce traitement supplémentaire, mais dans tous les cas je corrigerai ça
0
Tintin2256 Messages postés 25 Date d'inscription mardi 3 octobre 2017 Statut Membre Dernière intervention 18 septembre 2023
6 oct. 2017 à 11:27
Salut Whismeril,

Ok merci de tes explications.

Te prends pas le chou non plus, c'est pas à la seconde près. Tu n'es pas rémunéré pour ça donc, je ne vais pas t'imposer des délais non plus. C'est déjà super sympa de ta part de donner des coups de pattes comme ça.
0
Tintin2256 Messages postés 25 Date d'inscription mardi 3 octobre 2017 Statut Membre Dernière intervention 18 septembre 2023
6 oct. 2017 à 16:01
Bon, j'ai un peu plus approfondi mes tests et mis en marche mon neurones et j'ai trouvé les correctifs adaptés à mon besoin.
Du coup, j'ai supprimé le "Regex" qui, dans mon cas, n'est pas utile et qui me créait un bug
J'ai modifié un poil le code pour la textBox et ça fonctionne. Je te redonne le code global

Voici pour les classes:
    class LDExchangeFile
    {
        public LDExchangeFile()
        {
            Compagnie = "Schneider Automation";
            Produit = "Unity Pro XL V7.0 - 120823C";
            DateFileHeader = new DateTime(2017, 10, 4, 9, 31, 18);
            Contenu = "Fichier source LD";
            DTDVersion = "41";
            Nom = "NVAAP_AP124";
            Version = "0.0.1";
            DateContentHeader = new DateTime(2016, 7, 29, 18, 48, 41);
            Prog = new LeProgramme();
        }

        public string Compagnie { get; set; }

        public string Produit { get; set; }

        public string Contenu { get; set; }

        public string DTDVersion { get; set; }

        public DateTime DateFileHeader { get; set; }

        public string Nom { get; set; }

        public string Version { get; set; }

        public DateTime DateContentHeader { get; set; }

        public LeProgramme Prog { get; set; }

        public void AddElementsLignes(params ElementLigne[] Elements)
        {
            Ligne ligne = new Ligne();
            ligne.Elements = Elements.ToList();
            Prog.LdSource.Elements.Add(ligne);
        }

        public void AddTextBox(int Y)
        {
            Prog.LdSource.Elements.Add(new TexteBox { Taille = new Size(0, Y) });
        }

        public void Serialise(string Filename)
        {

            var toto = (from l in Prog.LdSource.Elements.OfType<Ligne>()
                        from fb in l.Elements.OfType<FFBBlock>()
                        select new { Nom = fb.NomInstance, Type = fb.NomType });

            XDocument xdoc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
             new XElement("LDExchangeFile",
                new XElement("fileHeader", new XAttribute("company", Compagnie), new XAttribute("product", Produit), new XAttribute("dateTime", string.Format("date_and_time#{0:yyyy-M-d-H:m:s}", DateFileHeader)), new XAttribute("content", Contenu), new XAttribute("DTDVersion", DTDVersion)),
                new XElement("contentHeader", new XAttribute("name", Nom), new XAttribute("version", Version), new XAttribute("dateTime", string.Format("date_and_time#{0:yyyy-M-d-H:m:s}", DateContentHeader))),
                Prog.Serialize,
                new XElement("dataBlock",
                    from x in toto
                    select new XElement("variables", new XAttribute("name", x.Nom), new XAttribute("typeName", x.Type))
                    )
                    )
                    );

            string texte = xdoc.ToString().Replace("  ", "\t");

            File.WriteAllText(Filename, texte);
        }
    }

    class LeProgramme
    {
        public LeProgramme()
        {
            Nom = "ECH130011_Vannes_ASI";
            Type = "section";
            Tache = "MAST";
            LdSource = new LDSource();
        }

        public string Nom { get; set; }

        public string Type { get; set; }

        public string Tache { get; set; }

        public LDSource LdSource { get; set; }

        public XElement Serialize
        {
            get
            {
                return new XElement("program",
                    new XElement("identProgram", new XAttribute("name", Nom), new XAttribute("type", Type), new XAttribute("task", Tache)),
                    LdSource.Serialize
                    );
            }
        }
    }

    class LDSource
    {
        public LDSource()
        {
            NbreColonnes = 11;
            Elements = new List<NetworkLDElement>();
        }

        public int NbreColonnes { get; set; }

        public List<NetworkLDElement> Elements { get; set; }

        public XElement Serialize
        {
            get
            {
                return new XElement("LDSource", new XAttribute("nbColumns", NbreColonnes),
                    new XElement("networkLD",
                    from e in Elements
                    select e.Serialize
                ));
            }
        }
    }

    abstract class NetworkLDElement
    {
        public abstract XElement Serialize { get; }
    }

    class Ligne : NetworkLDElement
    {
        public List<ElementLigne> Elements { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("typeLine",
                    from l in Elements
                    select l.Serialize);
            }
        }
    }

    abstract class ElementLigne
    {
        public abstract XElement Serialize { get; }
    }

    class LeContact : ElementLigne
    {
        public LeContact()
        {
            Type = "openContact";
            Nom = "false";
        }

        public string Type { get; set; }

        public string Nom { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("contact", new XAttribute("typeContact", Type), new XAttribute("contactVariableName", Nom));
            }
        }
    }

    class HLink : ElementLigne
    {
        public HLink()
        {
            NbreCells = 9;
        }

        public int NbreCells { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("HLink", new XAttribute("nbCells", NbreCells));
            }
        }

    }

    class Coil : ElementLigne
    {
        public Coil(string NomVariable)
        {
            Type = "coil";
            this.NomVariable = NomVariable;
        }

        public string Type { get; set; }//si les types sont prédéfinis, on pourrait mettre un enum, ce serait valable plus haut aussi

        public string NomVariable { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("coil", new XAttribute("typeCoil", Type), new XAttribute("coilVariableName", NomVariable));
            }
        }

    }

    class EmptyLine : ElementLigne
    {
        public EmptyLine()
        {
            Nombre = 1;
        }

        public int Nombre { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("emptyLine", new XAttribute("nbRows", Nombre));
            }
        }

    }

    class EmptyCell : ElementLigne
    {
        public EmptyCell()
        {
            Nombre = 4;
        }

        public int Nombre { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("emptyCell", new XAttribute("nbCells", Nombre));
            }
        }

    }

    class FFBBlock : ElementLigne
    {
        public FFBBlock(string InstanceName)
        {
            NomInstance = InstanceName;
            NomType = "DFB_Valve";
            AdditionnalPinNumber = 0;
            EnEnO = true;
            Taille = new Size(12, 6);
            ExecAfter = "";
            Elements = new List<LaVariable>();
        }

        public string NomInstance { get; set; }

        public string NomType { get; set; }

        public int AdditionnalPinNumber { get; set; }

        public bool EnEnO { get; set; }

        public Size Taille { get; set; }

        public Point Position { get; set; }

        public string ExecAfter { get; set; }

        public List<LaVariable> Elements { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("FFBBlock", new XAttribute("instanceName", NomInstance), new XAttribute("typeName", NomType), new XAttribute("additionnalPinNumber", AdditionnalPinNumber), new XAttribute("enEnO", EnEnO), new XAttribute("width", Taille.Width), new XAttribute("height", Taille.Height),
                    new XElement("objPosition", new XAttribute("posX", Position.X), new XAttribute("posY", Position.Y)),
                    new XElement("descriptionFFB", new XAttribute("execAfter", ExecAfter),
                        from e in Elements
                        select e.Serialize
                )
                    );
            }
        }
    }

    class LaVariable
    {
        public LaVariable(bool Input, string FormalParameter, bool? EffectiveParameter = null)
        {
            InvertedPin = false;
            this.FormalParameter = FormalParameter;
            this.EffectiveParameter = EffectiveParameter;
            input = Input;
        }

        bool input;

        public bool InvertedPin { get; set; }

        public string FormalParameter { get; set; }

        public bool? EffectiveParameter { get; set; }

        public XElement Serialize
        {
            get
            {
                return new XElement(input ? "inputVariable" : "outputVariable", new XAttribute("invertedPin", InvertedPin), new XAttribute("formalParameter", FormalParameter), EffectiveParameter == null ? null : new XAttribute("effectiveParameter", EffectiveParameter));
            }
        }
    }

    class TexteBox : NetworkLDElement
    {
        public TexteBox()
        {
            Taille = new Size(11, 1);
            Texte = "Gestion de la vanne de bypass Sortie Préchauffeur.";
            Position = new Point(0, 0);
        }

        public Size Taille { get; set; }

        public string Texte { get; set; }

        public Point Position { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("textBox", new XAttribute("posY", Position.Y),new XAttribute("width", "11"), new XAttribute("height", "1"), Texte, new XElement("objPosition", new XAttribute("posX", Position.X), new XAttribute("posY", Position.Y)));
            }
        }
    }
}


La fonction d'appel:

 LDExchangeFile test = new LDExchangeFile();

            test.AddElementsLignes(new EmptyLine());
            test.AddElementsLignes(new LeContact(), new HLink(), new Coil("DFB_Valve_4.X"));
            test.AddElementsLignes(new EmptyLine());
            FFBBlock block = new FFBBlock("DFB_Valve_4");
            block.Position = new Point(4,3);
            block.Elements = new List<LaVariable> { new LaVariable(true,"EN"), new LaVariable(true,"ZsOn", false), new LaVariable(true,"ZsOff", false), new LaVariable(true, "IN"), new LaVariable(true, "OUT"), new LaVariable(false,"ENO"), new LaVariable(false,"Xv") };
            test.AddElementsLignes(new EmptyCell { Nombre = 4 }, block , new EmptyCell { Nombre = 5 });
            test.AddElementsLignes(new HLink { NbreCells = 4 }, new EmptyCell { Nombre = 7 });
            test.AddElementsLignes(new EmptyLine { Nombre = 6 });
            test.AddElementsLignes(new LeContact(), new HLink(), new Coil("DFB_Valve_5.X"));
            test.AddElementsLignes(new EmptyLine());
            FFBBlock block2 = new FFBBlock("DFB_Valve_5");
            block2.Position = new Point(4,13);
            block2.Elements = new List<LaVariable>(block.Elements);
            test.AddElementsLignes(new EmptyCell { Nombre = 4 }, block2 , new EmptyCell { Nombre = 5 });
            test.AddElementsLignes(new HLink { NbreCells = 4 }, new EmptyCell { Nombre = 7 });
            test.AddElementsLignes(new EmptyLine { Nombre = 83 });
            test.AddTextBox(10);
            test.AddTextBox(0);

            test.Serialise(NomDossierDest.Text + @"\testTintin.xml");
        }



Encore un grand merci à toi car, grâce à cette méthode, je vais pouvoir pousser plus loin et générer d'autre bout de code.

Bon week end
0
Tintin2256 Messages postés 25 Date d'inscription mardi 3 octobre 2017 Statut Membre Dernière intervention 18 septembre 2023
Modifié le 9 oct. 2017 à 12:00
Salut Whismeril,

J'ai essayé de l'optimisé mais je crois que j'y ai été un peu fort et il ne fonctionne plus... En fait, j'avais mal exprimé ma demande et on balançait pas mal de paramètres "inutiles". Du coup, afin de simplifier et que d'autres personnes de ma boite puisse reprendre le code plus tard facilement, je voulais garder seulement les paramètres utiles.

Je te redonne le code modifié si tu peux le regarder quand tu aura 5min, ce serait top.

class LDExchangeFile
    {
        public LDExchangeFile(string NomEquipement)
        {
            Prog = new LeProgramme(NomEquipement);
        }

        public LeProgramme Prog { get; set; }

        public void AddElementsLignes(params ElementLigne[] Elements)
        {
            Ligne ligne = new Ligne();
            ligne.Elements = Elements.ToList();
            Prog.LdSource.Elements.Add(ligne);
        }

        public void AddTextBox(string Com, int Y)
        {
            Prog.LdSource.Elements.Add(new TexteBox (Com, Y));
        }

        public void Serialise(string Filename)
        {

            var toto = (from l in Prog.LdSource.Elements.OfType<Ligne>()
                        from fb in l.Elements.OfType<FFBBlock_Valve>()
                        select new { Nom = fb.NomVanne });

            XDocument xdoc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
             new XElement("LDExchangeFile",
                new XElement("fileHeader", new XAttribute("company", "Schneider Automation"), new XAttribute("product", "Unity Pro XL V7.0 - 120823C"), new XAttribute("dateTime", "date_and_time#2017-10-4-9:31:18")), new XAttribute("content", "Fichier source LD"), new XAttribute("DTDVersion", "41")),
                new XElement("contentHeader", new XAttribute("name", "NVAAP_AP124"), new XAttribute("version", "0.0.1"), new XAttribute("dateTime", "date_and_time#2016-7-29-18:48:41")),
                Prog.Serialize,
                new XElement("dataBlock",
                    from x in toto
                    select new XElement("variables", new XAttribute("name", x.Nom), new XAttribute("typeName", "DFB_Valve"))
                    ));

            string texte = xdoc.ToString().Replace("  ", "\t");

            File.WriteAllText(Filename, texte);
        }
    }

    class LeProgramme
    {
        public LeProgramme(string Nom)
        {
            this.Nom = Nom;
            LdSource = new LDSource();
        }

        public string Nom { get; set; }

        public LDSource LdSource { get; set; }

        public XElement Serialize
        {
            get
            {
                return new XElement("program",
                    new XElement("identProgram", new XAttribute("name", Nom), new XAttribute("type", "section"), new XAttribute("task", "MAST")),
                    LdSource.Serialize
                    );
            }
        }
    }

    class LDSource
    {
        public LDSource()
        {
            Elements = new List<NetworkLDElement>();
        }

        public List<NetworkLDElement> Elements { get; set; }

        public XElement Serialize
        {
            get
            {
                return new XElement("LDSource", new XAttribute("nbColumns", "11"),
                    new XElement("networkLD",
                    from e in Elements
                    select e.Serialize
                ));
            }
        }
    }

    abstract class NetworkLDElement
    {
        public abstract XElement Serialize { get; }
    }

    class Ligne : NetworkLDElement
    {
        public List<ElementLigne> Elements { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("typeLine",
                    from l in Elements
                    select l.Serialize);
            }
        }
    }

    abstract class ElementLigne
    {
        public abstract XElement Serialize { get; }
    }

    class LeContact : ElementLigne
    {
        public override XElement Serialize
        {
            get
            {
                return new XElement("contact", new XAttribute("typeContact", "openContact"), new XAttribute("contactVariableName", "false"));
            }
        }
    }

    class HLink : ElementLigne
    {
        public HLink(int NbreCells)
        {
            this.NbreCells = NbreCells;
        }

        public int NbreCells { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("HLink", new XAttribute("nbCells", NbreCells));
            }
        }

    }

    class Coil : ElementLigne
    {
        public Coil(string NomVariable)
        {
            this.NomVariable = NomVariable;
        }

        public string NomVariable { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("coil", new XAttribute("typeCoil", "coil"), new XAttribute("coilVariableName", NomVariable));
            }
        }

    }

    class EmptyLine : ElementLigne
    {
        public EmptyLine(int Nombre)
        {
            this.Nombre = Nombre;
        }

        public int Nombre { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("emptyLine", new XAttribute("nbRows", Nombre));
            }
        }

    }

    class EmptyCell : ElementLigne
    {
        public EmptyCell(int Nombre)
        {
            this.Nombre = Nombre;
        }

        public int Nombre { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("emptyCell", new XAttribute("nbCells", Nombre));
            }
        }

    }

    class FFBBlock_Valve : ElementLigne
    {
        public FFBBlock_Valve(string InstanceName, int PosY, string NomCaptON, string NomCaptOFF)
        {
            this.NomVanne = InstanceName;
            this.PosY = PosY;
            this.NomCaptON = NomCaptON;
            this.NomCaptOFF = NomCaptOFF;
        }

        public string NomVanne { get; set; }

        public int PosY { get; set; }
        public string NomCaptON { get; set; }
        public string NomCaptOFF { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("FFBBlock", new XAttribute("instanceName", NomVanne), new XAttribute("typeName", "DFB_Valve"), new XAttribute("additionnalPinNumber", "0"), new XAttribute("enEnO", "true"), new XAttribute("width", "12"), new XAttribute("height", "6"),
                    new XElement("objPosition", new XAttribute("posX", "4"), new XAttribute("posY", PosY)),
                    new XElement("descriptionFFB", new XElement("inputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "EN")),
                                                   new XElement("inputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "ZsOn"), new XAttribute("effectiveParameter", NomCaptON)),
                                                   new XElement("inputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "ZsOff"), new XAttribute("effectiveParameter", NomCaptOFF)),
                                                   new XElement("inputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "IN")),
                                                   new XElement("inputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "OUT")),
                                                   new XElement("outputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "ENO")),
                                                   new XElement("outputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "Xv"), new XAttribute("effectiveParameter", NomVanne)),
                                                   new XAttribute("execAfter", "")
                )
                    );
            }
        }
    }

    class TexteBox : NetworkLDElement
    {
        public TexteBox(String Texte, int posY)
        {
            this.Texte = Texte;
            this.posY = posY;
        }

        public Size Taille { get; set; }

        public string Texte { get; set; }

        public int posY { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("textBox",new XAttribute("width", "11"), new XAttribute("height", "1"), Texte, new XElement("objPosition", new XAttribute("posX", 0), new XAttribute("posY", posY)));
            }
        }
    }
}



Mon FFBBlock est un bloc fonction que j'utilise dans mon logiciel d'automatisme pour gérer un élément (Vanne ou moteur). Je l'ai laissé comme ça afin que si une évolution se produit, on puisse le faire vite.

A présent, il ne créé plus le fichier malgré des demandes:

LDExchangeFile test = new LDExchangeFile("Test");

            test.AddElementsLignes(new EmptyLine(1));
            test.AddElementsLignes(new LeContact(), new HLink(9), new Coil("DFB_Valve_4.X"));
            test.AddElementsLignes(new EmptyLine(1));
            FFBBlock_Valve block = new FFBBlock_Valve("DFB_Valve_4",3,"test","test");
            test.AddElementsLignes(new EmptyCell(4), new FFBBlock_Valve("DFB_Valve_4", 3, "test", "test"), new EmptyCell (5));
            test.AddElementsLignes(new HLink(9), new EmptyCell(4));
            test.AddElementsLignes(new EmptyLine (6));
            test.AddElementsLignes(new LeContact(), new HLink(9), new Coil("DFB_Valve_5.X"));
            test.AddElementsLignes(new EmptyLine(1));
            test.AddElementsLignes(new EmptyLine(83));
            test.AddTextBox("Test_1",0);
            test.AddTextBox("Test_2", 10);

            test.Serialise(NomDossierDest.Text + @"\testTintin.xml");


Merci d'avance,

Quentin
0
Tintin2256 Messages postés 25 Date d'inscription mardi 3 octobre 2017 Statut Membre Dernière intervention 18 septembre 2023
9 oct. 2017 à 14:10
C'est bon, j'ai trouvé le problème. J'avais mal fait la partie
XDocument xdoc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
             new XElement("LDExchangeFile",
                new XElement("fileHeader", new XAttribute("company", "Schneider Automation"), new XAttribute("product", "Unity Pro XL V7.0 - 120823C"), new XAttribute("dateTime", "date_and_time#2017-10-4-9:31:18")), new XAttribute("content", "Fichier source LD"), new XAttribute("DTDVersion", "41")),
                new XElement("contentHeader", new XAttribute("name", "NVAAP_AP124"), new XAttribute("version", "0.0.1"), new XAttribute("dateTime", "date_and_time#2016-7-29-18:48:41")),
                Prog.Serialize,
                new XElement("dataBlock",
                    from x in toto
                    select new XElement("variables", new XAttribute("name", x.Nom), new XAttribute("typeName", "DFB_Valve"))
                    ));


Je l'ai corrigé et ça donne ça:

class LDExchangeFile
    {
        public LDExchangeFile(string NomEquipement)
        {
            Prog = new LeProgramme(NomEquipement);
        }

        public LeProgramme Prog { get; set; }

        public void AddElementsLignes(params ElementLigne[] Elements)
        {
            Ligne ligne = new Ligne();
            ligne.Elements = Elements.ToList();
            Prog.LdSource.Elements.Add(ligne);
        }

        public void AddTextBox(string Com, int Y)
        {
            Prog.LdSource.Elements.Add(new TexteBox (Com, Y));
        }

        public void Serialise(string Filename)
        {

            var toto = (from l in Prog.LdSource.Elements.OfType<Ligne>()
                        from fb in l.Elements.OfType<FFBBlock_Valve>()
                        select new { Nom = fb.NomVanne });

          



            XDocument xdoc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
             new XElement("LDExchangeFile",
                new XElement("fileHeader", new XAttribute("company", "Schneider Automation"), new XAttribute("product", "Unity Pro XL V7.0 - 120823C"), new XAttribute("dateTime", "date_and_time#2017-10-4-9:31:18"), new XAttribute("content", "Fichier source LD"), new XAttribute("DTDVersion", "41")),
                new XElement("contentHeader", new XAttribute("name", "NVAAP_AP124"), new XAttribute("version", "0.0.1"), new XAttribute("dateTime", "date_and_time#2016-7-29-18:48:41")),
                Prog.Serialize,
                new XElement("dataBlock",
                    from x in toto
                    select new XElement("variables", new XAttribute("name", x.Nom), new XAttribute("typeName", "DFB_Valve"))
                    )));

            string texte = xdoc.ToString().Replace("  ", "\t");

            File.WriteAllText(Filename, texte);
        }
    }

    class LeProgramme
    {
        public LeProgramme(string Nom)
        {
            this.Nom = Nom;
            LdSource = new LDSource();
        }

        public string Nom { get; set; }

        public LDSource LdSource { get; set; }

        public XElement Serialize
        {
            get
            {
                return new XElement("program",
                    new XElement("identProgram", new XAttribute("name", Nom), new XAttribute("type", "section"), new XAttribute("task", "MAST")),
                    LdSource.Serialize
                    );
            }
        }
    }

    class LDSource
    {
        public LDSource()
        {
            Elements = new List<NetworkLDElement>();
        }

        public List<NetworkLDElement> Elements { get; set; }

        public XElement Serialize
        {
            get
            {
                return new XElement("LDSource", new XAttribute("nbColumns", "11"),
                    new XElement("networkLD",
                    from e in Elements
                    select e.Serialize
                ));
            }
        }
    }

    abstract class NetworkLDElement
    {
        public abstract XElement Serialize { get; }
    }

    class Ligne : NetworkLDElement
    {
        public List<ElementLigne> Elements { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("typeLine",
                    from l in Elements
                    select l.Serialize);
            }
        }
    }

    abstract class ElementLigne
    {
        public abstract XElement Serialize { get; }
    }

    class LeContact : ElementLigne
    {
        public override XElement Serialize
        {
            get
            {
                return new XElement("contact", new XAttribute("typeContact", "openContact"), new XAttribute("contactVariableName", "false"));
            }
        }
    }

    class HLink : ElementLigne
    {
        public HLink(int NbreCells)
        {
            this.NbreCells = NbreCells;
        }

        public int NbreCells { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("HLink", new XAttribute("nbCells", NbreCells));
            }
        }

    }

    class Coil : ElementLigne
    {
        public Coil(string NomVariable)
        {
            this.NomVariable = NomVariable;
        }

        public string NomVariable { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("coil", new XAttribute("typeCoil", "coil"), new XAttribute("coilVariableName", NomVariable));
            }
        }

    }

    class EmptyLine : ElementLigne
    {
        public EmptyLine(int Nombre)
        {
            this.Nombre = Nombre;
        }

        public int Nombre { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("emptyLine", new XAttribute("nbRows", Nombre));
            }
        }

    }

    class EmptyCell : ElementLigne
    {
        public EmptyCell(int Nombre)
        {
            this.Nombre = Nombre;
        }

        public int Nombre { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("emptyCell", new XAttribute("nbCells", Nombre));
            }
        }

    }

    class FFBBlock_Valve : ElementLigne
    {
        public FFBBlock_Valve(string InstanceName, int PosY, string NomCaptON, string NomCaptOFF)
        {
            this.NomVanne = InstanceName;
            this.PosY = PosY;
            this.NomCaptON = NomCaptON;
            this.NomCaptOFF = NomCaptOFF;
        }

        public string NomVanne { get; set; }

        public int PosY { get; set; }
        public string NomCaptON { get; set; }
        public string NomCaptOFF { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("FFBBlock", new XAttribute("instanceName", NomVanne), new XAttribute("typeName", "DFB_Valve"), new XAttribute("additionnalPinNumber", "0"), new XAttribute("enEnO", "true"), new XAttribute("width", "12"), new XAttribute("height", "6"),
                    new XElement("objPosition", new XAttribute("posX", "4"), new XAttribute("posY", PosY)),
                    new XElement("descriptionFFB", new XElement("inputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "EN")),
                                                   new XElement("inputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "ZsOn"), new XAttribute("effectiveParameter", NomCaptON)),
                                                   new XElement("inputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "ZsOff"), new XAttribute("effectiveParameter", NomCaptOFF)),
                                                   new XElement("inputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "IN")),
                                                   new XElement("inputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "OUT")),
                                                   new XElement("outputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "ENO")),
                                                   new XElement("outputVariable", new XAttribute("invertedPin", "false"), new XAttribute("formalParameter", "Xv"), new XAttribute("effectiveParameter", NomVanne)),
                                                   new XAttribute("execAfter", "")
                )
                    );
            }
        }
    }

    class TexteBox : NetworkLDElement
    {
        public TexteBox(String Texte, int posY)
        {
            this.Texte = Texte;
            this.posY = posY;
        }

        public Size Taille { get; set; }

        public string Texte { get; set; }

        public int posY { get; set; }

        public override XElement Serialize
        {
            get
            {
                return new XElement("textBox",new XAttribute("width", "11"), new XAttribute("height", "1"), Texte, new XElement("objPosition", new XAttribute("posX", 0), new XAttribute("posY", posY)));
            }
        }
    }
}



Un grand merci pour ton aide Whismeril une nouvelle fois.

Bonne journée
0
Whismeril Messages postés 19029 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 26 avril 2024 656 > Tintin2256 Messages postés 25 Date d'inscription mardi 3 octobre 2017 Statut Membre Dernière intervention 18 septembre 2023
9 oct. 2017 à 17:55
De rien pour le coup...
0
Rejoignez-nous