khurram
khurram

Reputation: 1070

making XML nodes dynamically

I am calling an API and have to send a xml request in C# with data in different nodes. How can make xml dynamically and with nodes in incremental naming.

For example

<?xml version="1.0" encoding="UTF-8" ?>
<addCustomer>
    <FirstName_1>ABC</FirstName_1>
    <LastName_1>DEF</LastName_1>
    <FirstName_2>GSH</FirstName_2>
    <LastName_2>ADSF</LastName_2>
</addCustomer>

The problem is making xml nodes with incremental names like FirstName_1,FirstName_2,FirstName_3 and so on.

Upvotes: 1

Views: 1220

Answers (3)

gunr2171
gunr2171

Reputation: 17447

I know your pain; having to deal with 3rd party APIs can be big pain.

Instead of using StringBuilder you can use XElement.

public void AddCustomerInfo(string firstName, string lastName, int index, XElement root)
{
    XElement firstNameInfo = new XElement("FirstName_" + index);
    firstNameInfo.Value = firstName;

    XElement lastNameInfo = new XElement("LastName_" + index);
    lastNameInfo.Value = lastName;

    root.Add(firstNameInfo);
    root.Add(lastNameInfo);
}

Then call the function as the following:

XElement rootElement = new XElement("addCustomer");
AddCustomerInfo("ABC", "DEF", 1, rootElement);

Put that line inside a loop and you're all set.

Upvotes: 2

Shai Cohen
Shai Cohen

Reputation: 6249

I think the simplest solution would be the best here:

Assuming you have a collection of Customer objects called Customers...

StringBuilder xmlForApi = new StringBuilder();
int customerCounter = 1;
foreach(Customer c in Customers)
{
    xmlForApi.AppendFormat("<FirstName_{0}>{1}</FirstName_{0}><LastName_{0}>{2}</LastName_{0}>", customerCounter, c.FirstName, c.LastName)
    customerCounter++;
}

Upvotes: 0

DavidEdwards
DavidEdwards

Reputation: 593

Would a customer have more than one FirstName and more than one LastName? If each FirstName and LastName pairs represent a different customer then your xml should look something like....

<?xml version="1.0" encoding="UTF-8" ?>
<AddCustomers>
     <Customer>
          <FirstName>ABC</FirstName>
          <LastName>DEF</LastName>
     </Customer>
     <Customer>
          <FirstName>GSH</FirstName>
          <LastName>ASDF</LastName>
     </Customer>
</AddCustomers>

If you absolutely have to do it the way that you did it in your example, I do not see any way to do this except just using a string_builder and create it yourself within a for loop while incrementing your integer to add to the end of each First and last name attributes. This is not really how xml is supposed to work.

Upvotes: 2

Related Questions