[英]how to use linq to convert list of string,<t> into XML
我試圖獲得將數據轉換為XML的鏈接。 我幾乎可以使用的LINQ表達式是:
XElement xml = new XElement("contacts",
lstEmailData.Select(i => new XElement("Data",
new XAttribute("URL", i.WebPage ),
new XAttribute("emails", i.Emails.ToArray() + " , ")
)));
其中lstEmailData定義為:
List<PageEmail> lstEmailData = new List<PageEmail>();
lstEmailData.Add(new PageEmail("site2", new List<string>() {
"MyHotMail@NyTimes.com", "contact_us@ml.com" }));
其中PageEmail是:
class PageEmail
{
public string WebPage { get; set; }
public List<string> Emails { get; set; }
public PageEmail(string CurWebPage, List<string> CurEmails)
{
this.WebPage = CurWebPage;
this.Emails = CurEmails;
}
}
LINQ的XML輸出關閉,我沒有收到電子郵件列表:
<contacts>
<Data URL="site1" emails="System.String[] , " />
<Data URL="site2" emails="System.String[] , " />
</contacts>
如何將每個i.Email放入自己的xml節點中?
我猜您正在嘗試將所有電子郵件存儲在emails
屬性中。 使用String.Join :-
new XAttribute("emails", String.Join(",", i.Emails)
當您將對象作為第二個參數傳遞給XAttribute
構造函數時。 它調用ToString
方法。 在數組上調用ToString
的結果是數組的名稱(因此得到System.String[]
)。要顯示其中的字符串,應使用String.Join
代替。
XElement xml = new XElement("contacts",
lstEmailData.Select(i => new XElement("Data",
new XAttribute("URL", i.WebPage ),
new XAttribute("emails", String.Join(",", i.Emails))
)));
如何將每個i.Email放入自己的xml節點中? 嘗試這個:
XElement xml = new XElement("contacts",
lstEmailData.Select(pageEmail =>
new XElement("Data", new XAttribute("Url",pageEmail.WebPage),
pageEmail.Emails.Select(email => new XElement("Email",email))
)
)
);
結果:
<contacts>
<Data Url="site2">
<Email>MyHotMail@NyTimes.com</Email>
<Email>contact_us@ml.com</Email>
</Data>
</contacts>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.