-1

I am trying to get link to convert data into XML. The LINQ expression i have almost working is:

XElement xml = new XElement("contacts",
lstEmailData.Select(i => new XElement("Data",
                            new XAttribute("URL", i.WebPage ),
                                new XAttribute("emails", i.Emails.ToArray()  + " , ")
)));

where lstEmailData is defined as:

List<PageEmail> lstEmailData = new List<PageEmail>();
lstEmailData.Add(new PageEmail("site2", new List<string>() {
    "MyHotMail@NyTimes.com", "contact_us@ml.com" }));

where PageEmail is:

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;
    }
}

the XML output from the LINQ is off, I'm not getting the email list:

<contacts>
  <Data URL="site1" emails="System.String[] , " />
  <Data URL="site2" emails="System.String[] , " />
</contacts>

How to get each of the i.Emails into their own xml nodes?

kacalapy
  • 9,806
  • 20
  • 74
  • 119
  • figured it out by this article:http://blogs.msdn.com/b/wriju/archive/2008/02/18/linq-to-xml-creating-complex-xml-through-linq.aspx – kacalapy Oct 13 '15 at 15:36
  • XElement xml = new XElement("SiteData", lstEmailData.Select(i => new XElement("WebSite", new XAttribute("URL", i.WebPage), from o in i.Emails select new XElement("mail", o.ToString() ) ))); – kacalapy Oct 13 '15 at 15:36

2 Answers2

4

I guess you are trying to store all the emails in emails attribute. Use String.Join:-

new XAttribute("emails", String.Join(",", i.Emails)
Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
2

When you pass an object as a second argument to the XAttribute constructor. It calls the ToString method on it. The result of calling ToString on an array is the array's name (So you get System.String[]) To show the strings inside it, you should do use String.Join instead.

XElement xml = new XElement("contacts",
lstEmailData.Select(i => new XElement("Data",
                            new XAttribute("URL", i.WebPage ),
                                new XAttribute("emails", String.Join(",", i.Emails))
)));

How to get each of the i.Emails into their own xml nodes? Try this:

XElement xml = new XElement("contacts",
    lstEmailData.Select(pageEmail =>
        new XElement("Data", new XAttribute("Url",pageEmail.WebPage), 
            pageEmail.Emails.Select(email => new XElement("Email",email))
        )
    )
);

Results:

<contacts>
  <Data Url="site2">
    <Email>MyHotMail@NyTimes.com</Email>
    <Email>contact_us@ml.com</Email>
  </Data>
</contacts>
wingerse
  • 3,670
  • 1
  • 29
  • 61