1

I need to add a variable number of XElements to my XML document based on the value of e(which is different each time). I think I need to do something similar to what I have below but the below code gives me 6 errors. These are:

  • Only assignment, call, increment, decrement, and new object expressions can be used as a statement x 2
  • Invalid expression term 'for'/')'/')'
  • ; expected

    int e = 3;
    
    doc.Root.Add(new XElement(ns + "LineItemList",
    
    for(int i = 0; i <= e; i++)
    {
        new XElement("ItemNumber", i.ToString());
    }
    
    ));
    

What am I doing wrong?

To put my question another way, my understanding is that to have my LineItem elements inside my LineItemListelement, I need to put my LineItem's inside the declaration of LineItemList.

If somebody could tell me how to explicitly open and close elements, instead of them being opened and closed implicitly this would help a lot.

3 Answers 3

6

Try this one:

int e = 3;
XDocument doc = new XDocument(
          new XElement(ns + "LineItemList",
               Enumerable.Range(0, e).Select(i => new XElement("ItemNumber", i))
          ));
Sign up to request clarification or add additional context in comments.

Comments

2

I think you are looking for:

int e = 3;
XElement lineElement = new XElement(ns + "LineItemList");
doc.Root.Add(lineElement);
for(int i = 0; i <= e; i++) 
{ 
  XElement itemElement = new XElement("ItemNumber", i.ToString());
  lineElement.Add(itemElement)
}

Comments

0

You cannot use a for loop inside a method call.

Maybe you want to do something like this:

for(int i = 0; i <= e; i++) { 
    XElement element = new XElement("ItemNumber", i.ToString()); 
    doc.Root.Add(element);
}

I didn't test this code.

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.