在c#中使用xelement创建动态xml [英] Create dynamic xml using xelement in c#

查看:66
本文介绍了在c#中使用xelement创建动态xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如您所见,条件是否正常,应将参数添加到 RejectedXmlList 中,但我收到此异常:

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

推荐答案

您正在尝试使用多个 根元素Parameters 中的每个Parameter 一个你不能这样做,因为XML 标准不允许:

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.

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

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.

相反,添加一个根元素,例如,然后将您的 xelement 子项添加到其中:

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

示例 fiddle.

这篇关于在c#中使用xelement创建动态xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆