在 C# 中使用 xelement 创建动态 xml

Create dynamic xml using xelement in c#

我想使用 XElement 创建 xml,如您所见:

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);
    }
}

如您所见,如果条件正常,则应将参数添加到 RejectedXmlList,但我却收到此异常:

This operation would create an incorrectly structured document.

注意,第一个参数添加成功。只有当添加第二个时,我才会得到异常。

预期的结果应该是这样的:

<co>2</co>
<o2>2</o2>
....

您正在尝试创建具有多个 XDocumentroot elements, one for each Parameter in Parameters You can't do that because the XML standard 不允许:

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

LINQ to XML API 强制执行此约束,抛出您在尝试向文档添加第二个根元素时看到的异常。

而是添加一个根元素,例如<Rejectedparameters>,然后将你的 xelement children 添加到其中:

// 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);
    }
}

示例 fiddle.