c# - 在c#中使用xelement创建动态xml

标签 c# xml xelement

我想使用 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>
....

最佳答案

您正在尝试创建 XDocument多个 root elements ,各一个ParameterParameters你不能这样做,因为 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 .

关于c# - 在c#中使用xelement创建动态xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44993196/

相关文章:

c# - 在泛型集合上使用 except()

xml - 使用 XQuery 将 XML 数据转换为 CSV 字符串

asp.net - 如何避免 System.Xml.Linq.XElement 转义 HTML 内容?

C#对象引用问题

c# - Clean Architecture 中的 'Use Case Interactor' 和 'Service' 有什么区别?

java - 我知道如何通过按钮打开相机,但我不知道如何更改拍摄照片的位置,我该怎么做?

c# - 在 C# Web 应用程序中访问内容文件

c# - 为什么将 xml 根目录作为 xpath 的一部分时我没有得到任何结果

c# - 有条件地为 child 启用/禁用自动格式化

c# - PerHttpRequestLifeTimeManager for Unity with Web API 和 OWIN