开发者

Create XML using LINQ-to-XML API

I want to create an XML which looks like

<Records FileUniqueId="1234567" Source="CCC">
  <Record InfNumber="122354" AgencyNumber="017"></Record>
  <Record InfNumber="122355" AgencyNumber="018"></Record>
 <Record InfNumber="122356" AgencyNumber="018"></Record>
</Records>
XElement responseXML = new XElement("Records");
                responseXML.SetAttributeValue(BusinessConstants.colFileUniqueID, _fileUniqueId);
                responseXML.SetAttributeValue(BusinessConstants.colSourceName, _sourceName);

                foreach (InfringementEntity ie in iLES.infringementEntities)
                {
                    responseXML.Add(new XElement("Record"));
                    XElement record = responseXML.Element("Record");

                    record.SetAttributeValue(BusinessConstants.colInfringementNumber, ie.infringementNumber);
               开发者_开发技巧     record.SetAttributeValue(BusinessConstants.colIssueAgency, ie.issueAgency);
                }

I am using the above code to generate the XML, but the issue is that when I am setting the attributes for a Record, it overwrites the attributes of 1st record everytime.

So the XML I am getting is:

 <Records FileUniqueId="1234567" Source="CCC">
     <Record InfNumber="122356" AgencyNumber="018"></Record>
      <Record/>
      <Record/>
    </Records>

please help.


Yes, it's overwriting the attributes of the first record because you're telling it to - you're not using the Record element you've just created. You could do it like this:

foreach (InfringementEntity ie in iLES.infringementEntities)
{
    XElement newRecord = new XElement("Record");
    newRecord.SetAttributeValue(BusinessConstants.colInfringementNumber,
                                ie.infringementNumber);
    newRecord.SetAttributeValue(BusinessConstants.colIssueAgency,
                                responseXML.Add(newRecord);
}

... but there are rather more idiomatic ways of doing it, such as:

XElement responseXML = new XElement("Records",
    iLes.infringementEntities.Select(ie => new XElement("Record",
        new XAttribute(BusinessConstants.colInfringementNumber,
                       ie.infringementNumber),
        new XAttribute(BusinessConstants.colIssueAgency, ie.issueAgency))));

That replaces the whole of your code, including the foreach statement.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜