Create dynamic xml using xelement in c#

允我心安 提交于 2019-12-11 07:07:14

问题


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.



来源:https://stackoverflow.com/questions/44993196/create-dynamic-xml-using-xelement-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!