mishan
mishan

Reputation: 1217

XDocument Add multiple XElements

In my Windows Phone 8 C#/XAML .NET 4.5 Project, I'm trying to create an XDocument with similar structure:

<element1>
  <subelement1>
  </subelement1>
  <subelement2>
     ...etc...
  </subelement2>
</element1>

<element2>
  <subelement1>
  </subelement1>
  <subelement2>
     ...etc...
  </subelement2>
</element2>

The method creating the document looks like (simplified for the question purposes):

... createXML()
{
    XDocument doc = new XDocument();

    XElement elem1 = new XElement("element1");
    elem1.Add(new XElement("subelement1"));
    XElement elem2 = new XElement("element2");

    doc.Add(elem1);
    doc.Add(elem2);
}

But I keep getting InvalidOperationException saying that it would create a invalid document structure.

I know why - it would cause the document to have multiple "root nodes" - but I effectively need it that way.

This structure is needed for webservice done by third party, which recieves the document as a string.

So the question is "How to achieve this structure? Should I use some other XObject instead?"

(I know that probably the most simple solution would be to use collection of XElements...just askin' if there is another way out of curiosity)

Upvotes: 1

Views: 4282

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726779

The structure that you specified at the top of the post is illegal, because valid XML documents must have a single root element; your document has two elements at the top level, which is not allowed.

You can solve this problem by adding a root element at creation time, and then discarding it when reading the document;

document = new XDocument(new XElement("root", elem1, elem2));

Upvotes: 2

Related Questions