Search code examples
c#xmlxelement

How to use foreach loop inside a Xelement in c#


 XElement doc = null;
 doc = new XElement("root");
 foreach (var content in emailContents)
                                    {
    doc.Add(new XElement("Email",
            new XElement("FromAddress", content.FromAddress),
            new XElement("EmailReceivedOn", content.receivedOnemail),
            new XElement("Subject", content.subject),
            new XElement("Body", content.body)));
    // I want to add the below code after the body element is created in the xml inside the email element section; How to do the same?
     foreach (var attachment in content.attachments)
        {
          doc.Add(new XElement("attachmentname"), attachment.Filename),
          doc.Add(new XElement(("attachmentpath"), attachment.Filepath)        
        }
}

Basically content.attachment is a list of attachment name and i want to add the list just after the body element. How to do the same?


Solution

  • It's fairly easy to do it in one go:

    var doc =
        new XElement("root",
            new XElement("Email",
                new XElement("FromAddress", content.FromAddress),
                new XElement("EmailReceivedOn", content.receivedOnemail),
                new XElement("Subject", content.subject),
                new XElement("Body", content.body),
                content.attachments.Select(attachment =>
                    new XElement("attachment",
                        new XElement("attachmentname", attachment.Filename),
                        new XElement("attachmentpath", attachment.Filepath)))));
    

    I started with this sample data:

    var content = new
    {
        FromAddress = "FromAddress",
        receivedOnemail = "receivedOnemail",
        subject = "subject",
        body = "body",
        attachments = new []
        {
            new
            {
                Filename = "Filename",
                Filepath = "Filepath",
            },
        },
    };
    

    And I got this XML:

    <root>
      <Email>
        <FromAddress>FromAddress</FromAddress>
        <EmailReceivedOn>receivedOnemail</EmailReceivedOn>
        <Subject>subject</Subject>
        <Body>body</Body>
        <attachment>
          <attachmentname>Filename</attachmentname>
          <attachmentpath>Filepath</attachmentpath>
        </attachment>
      </Email>
    </root>