Ho la seguente struttura XML. L'elemento theElement
può contenere theOptionalList
elemento, o no:Come decorare/definire i membri della classe per un elemento XML facoltativo da utilizzare con XmlSerializer?
<theElement attrOne="valueOne" attrTwo="valueTwo">
<theOptionalList>
<theListItem attrA="valueA" />
<theListItem attrA="anotherValue" />
<theListItem attrA="stillAnother" />
</theOptionalList>
</theElement>
<theElement attrOne="anotherOne" attrTwo="anotherTwo" />
Che cosa è un modo pulito per esprimere la struttura corrispondente classe?
Sono abbastanza sicuro di quanto segue:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace MyNamespace
{
public class TheOptionalList
{
[XmlAttributeAttribute("attrOne")]
public string AttrOne { get; set; }
[XmlAttributeAttribute("attrTwo")]
public string AttrTwo { get; set; }
[XmlArrayItem("theListItem", typeof(TheListItem))]
public TheListItem[] theListItems{ get; set; }
public override string ToString()
{
StringBuilder outText = new StringBuilder();
outText.Append("attrOne = " + AttrOne + " attrTwo = " + AttrTwo + "\r\n");
foreach (TheListItem li in theListItems)
{
outText.Append(li.ToString());
}
return outText.ToString();
}
}
}
Così come:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace MyNamespace
{
public class TheListItem
{
[XmlAttributeAttribute("attrA")]
public string AttrA { get; set; }
public override string ToString()
{
StringBuilder outText = new StringBuilder();
outText.Append(" attrA = " + AttrA + "\r\n");
return outText.ToString();
}
}
}
Ma che dire per theElement
? Prendo l'elemento theOptionalList
come un tipo di matrice per fare in modo che legga ciò che trova nel file (nulla o uno) e poi controlla nel codice se è lì o no? O c'è un altro decoratore che posso fornire? Oppure funziona?
MODIFICA: Ho finito per utilizzare le informazioni da this answer.
Grazie per la risposta James. Immagino che questo gestisca un elemento 'theOptionalList' senza elementi, ma gestirà' theOptionalList' che non esiste affatto? (Forse non capisco cosa stai suggerendo.) Inoltre, non c'è schema per il mio formato; è tutto per accordo verbale tra me e un altro sviluppatore.:) – John
Non sono positivo, ma penso che l'uso di 'IsNullable' lo escluderebbe se l'array è nullo. –
Considera uno schema. È potentemente utile, per quanto piccolo, ed è un ottimo pezzo per il tuo "toolkit". – Gusdor