0

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.