2015-07-10 106 views
0
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)   
     } 
} 

基本上content.attachment是附件名称的列表,我想在body元素之后添加列表。如何做同样的事情?如何在c中的Xelement中使用foreach循环#

+0

只需指定'var email = new XElement(“Email”,...);'然后将其添加到'doc',然后添加它的附件? – dbc

回答

3

这是很容易做到一气呵成:

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

我开始用这个样本数据:

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

而且我得到了这个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> 
+0

我收到此错误 - >此方法不支持物化查询结果。 –

+1

@rohitsingh如果列表是来自数据库的查询,请在使用'Select()'前使用'.ToList()'。 – Default

+0

谢谢,现在工作 –

1

您正在将附件添加到根元素,而不是添加到电子邮件元素中。你可以像下面这样做。

XElement doc = null; 
doc = new XElement("root"); 
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))); 
var email=doc.Element("Email"); // get email element from root Element 
foreach (var attachment in content.attachments) 
    { 
     //Add attachemnt information to email element. 
     email.Add(new XElement("attachmentname"), attachment.Filename), 
     email.Add(new XElement(("attachmentpath"), attachment.Filepath)   
    }