Dynamic Nested XML Elements with LINQ

I am working on an open source project to wrap the UPS API in a C# library. I needed this functionality in a project and decided to just make it happen. You can see the source code as it gets updated here.

LINQ to XML is actually a very impressive part of .Net. Easy to use, intuitive and makes the C# code look just like the XML will. The last part of the library is to add a Dynamic Nested XML Elements using LINQ to list all the packages that will be sent to the API.

This is a little less intuitive and I am having a difficult time finding any good solutions to the issue. I don’t know the exact number of packages at any given moment so this part of the code needs to be more dynamic than the rest of the XML generation code. To make it even harder there are several nested elements that need to be created to accomplish this.

As I work through this I will post updates as I am sure this is not an uncommon issue.


After letting this one peculate all weekend long I came up with an idea that was kind of outside of the box (but not really). The original idea I had was to have a loop that would dynamically add the XML needed for each package. Unfortunately LINQ to XML is not set up to handle loops directly. You can’t do something like this:

Every element I looked at would only allow a string for the new elements name and the inner text for the tag or a list of elements that should be included. This latter part was something I could work with. I knew I could add a list of items, but just not in the full body of the XElement like above. I could however create a list of XElements and assign them to a tag later. This is what I would need to do. Except that I would need to create several other parts of the parent tag to make it work. Here is the final code.

So far this is one really minor hang up I have with LINQ to XML, not a deal breaker by any means. This is still a very powerful and easy to use library and after I thought about it more it makes sense. The syntax for the library is still easy to read and understand and everything still looks like XML in the end.

Should you require to create XML documents for any reason this would be my go to format.