简体   繁体   English

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

[英]Create dynamic xml using xelement in c#

I want to create xml using XElement as you can see: 如您所见,我想使用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);
    }
}

As you can see if the condition is OK the parameter should be added to RejectedXmlList but instead I get this exception: 如您所见,条件是否正常,应将参数添加到RejectedXmlList但我得到此异常:

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 each Parameter in Parameters You can't do that because the XML standard disallows it: 您正在试图创建一个XDocument根元素 ,每一个ParameterParameters ,你不能这样做,因为XML标准不允许它:

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. LINQ to XML API强制执行此约束,从而引发在尝试向文档中添加第二个根元素时看到的异常。

Instead, add a root element, eg <Rejectedparameters> , then add your xelement children to it: 而是添加一个根元素,例如<Rejectedparameters> ,然后向其中添加xelement子元素:

// 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 . 样品提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM