我有以下XML結構。該theElement
元素可以包含theOptionalList
元素,或不:如何裝飾/定義類成員與XmlSerializer的使用可選的XML元素?
<theElement attrOne="valueOne" attrTwo="valueTwo">
<theOptionalList>
<theListItem attrA="valueA" />
<theListItem attrA="anotherValue" />
<theListItem attrA="stillAnother" />
</theOptionalList>
</theElement>
<theElement attrOne="anotherOne" attrTwo="anotherTwo" />
什麼是表達對應的類結構的清潔方法是什麼?
我敢肯定如下:
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();
}
}
}
除了:
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();
}
}
}
但是有關theElement
?難道我拿theOptionalList
元素爲數組類型有它讀什麼它找到的文件(無論是什麼,或一個)中,然後在代碼檢查它是否是有或沒有?還是有另一個裝飾者,我可以提供?還是隻是工作?
編輯:我結束了使用從this answer信息。
感謝詹姆斯的迴應。我猜這將處理一個沒有元素的'TheOptionalList'元素,但是它會處理'根本不存在的'OptionalList'? (我可能不明白你的建議。)另外,我的格式沒有模式;這完全取決於我和其他開發者之間的口頭協議。:) – John
我不積極,但我認爲使用'IsNullable'會排除它,如果數組爲空。 –
考慮一個模式。它非常有用,無論多麼小,對你的'工具包'來說都是一件好事。 – Gusdor