如何在 C# 中的 Xelement 内使用 foreach 循环

roh*_*ngh 0 c# xml xelement

 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)        
        }
}
Run Code Online (Sandbox Code Playgroud)

基本上 content.attachment 是附件名称的列表,我想在 body 元素后面添加该列表。如何做同样的事情?

Eni*_*ity 5

一次性完成这件事相当容易:

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)))));
Run Code Online (Sandbox Code Playgroud)

我从这个样本数据开始:

var content = new
{
    FromAddress = "FromAddress",
    receivedOnemail = "receivedOnemail",
    subject = "subject",
    body = "body",
    attachments = new []
    {
        new
        {
            Filename = "Filename",
            Filepath = "Filepath",
        },
    },
};
Run Code Online (Sandbox Code Playgroud)

我得到了这个 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>
Run Code Online (Sandbox Code Playgroud)