簡體   English   中英

如何使用linq轉換字符串列表, <t> 轉換成XML

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM