-->

Create dynamic xml using xelement in c#

2019-08-03 21:30发布

问题:

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>
....

回答1:

You are trying to create an XDocument with multiple root elements, one for each Parameter in Parameters You can't do that because the XML standard disallows it:

There is exactly one element, called the root, or document element, no part of which appears in the content of any other element.

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 your xelement children to it:

// Allocate the XDocument and add an XML declaration.  
XDocument RejectedXmlList = new XDocument(new XDeclaration("1.0", "utf-8", null));

// At this point RejectedXmlList.Root is still null, so add a unique root element.
RejectedXmlList.Add(new XElement("Rejectedparameters"));

// Add elements for each Parameter to the root element
foreach (Parameter Myparameter in Parameters)
{
    if (true)
    {
        XElement xelement = new XElement(Myparameter.ParameterName, CurrentData.ToString());
        RejectedXmlList.Root.Add(xelement);
    }
}

Sample fiddle.



标签: c# xml xelement