I want to create xml using XElement
as you can see:
XDocument RejectedXmlList = new XDocument
(
new XDeclaration("1.0", "utf-8", null)
);
int RejectCounter = 0;
foreach (Parameter Myparameter in Parameters)
{
if (true)
{
XElement xelement = new XElement(Myparameter.ParameterName, CurrentData.ToString());
RejectedXmlList.Add(xelement);
}
}
As you can see if the condition is OK the parameter should be added to RejectedXmlList
but instead I get this exception:
This operation would create an incorrectly structured document.
Of note, the first parameter is added successfully. Only when the second one is added do I get the exception.
The expected result should be like this:
<co>2</co>
<o2>2</o2>
....
You are trying to create an
XDocument
with multiple root elements, one for eachParameter
inParameters
You can't do that because the XML standard disallows it:The LINQ to XML API enforces this constraint, throwing the exception you see when you try to add a second root element to the document.
Instead, add a root element, e.g.
<Rejectedparameters>
, then add yourxelement
children to it:Sample fiddle.