Mam następującą strukturę XML. Element theElement
może zawierać theOptionalList
element, czy nie:Jak ozdobić/zdefiniować elementy klasy dla opcjonalnego elementu XML do użycia z XmlSerializer?
<theElement attrOne="valueOne" attrTwo="valueTwo">
<theOptionalList>
<theListItem attrA="valueA" />
<theListItem attrA="anotherValue" />
<theListItem attrA="stillAnother" />
</theOptionalList>
</theElement>
<theElement attrOne="anotherOne" attrTwo="anotherTwo" />
Co to czysty sposób wyrazić odpowiedniej struktury klasowej?
jestem całkiem pewny, co następuje:
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();
}
}
}
Jak również:
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();
}
}
}
Ale co do theElement
? Czy biorę element theOptionalList
jako typ tablicowy, aby czytał, co znajduje się w pliku (nic lub jedno), a następnie sprawdzał kod, czy istnieje? Czy jest jeszcze inny dekorator, który mogę dostarczyć? Czy to po prostu działa?
EDIT: Skończyło się na wykorzystaniu informacji z this answer.
Dzięki za odpowiedź James. Zgaduję, że poradziłoby to z elementem 'theOptionalList' bez elementów, ale czy obsługiwałoby' TheOptionalList' w ogóle nieistniejącą? (Może nie rozumiem, co sugerujesz.) Ponadto nie ma schematu dla mojego formatu; to wszystko przez ustną umowę między mną a innym deweloperem.:) – John
Nie jestem pozytywny, ale myślę, że użycie 'IsNullable' spowoduje wykluczenie go, jeśli tablica ma wartość NULL. –
Rozważ schemat. Jest bardzo przydatny, jednak mały i jest świetnym elementem dla twojego "zestawu narzędzi". – Gusdor