简体   繁体   English

在C#中进行序列化期间,将字典中的其他元素添加到XML

[英]Add additional elements from a dictionary to the XML during serialization in C#

A part of the XML looks like this. XML的一部分看起来像这样。

<element>
    <subelment1>text</subelement1>
    <subelement2>text2</subelement2>
    ...
</element>

It has a lot of sub elements. 它有很多子元素。

I would like to add additional elements during the serialization, but the number and name is always different. 我想在序列化过程中添加其他元素,但是数字和名称始终不同。 So it will be something like this: 因此它将是这样的:

<element>
    <subelment1>text</subelement1>
    <subelement2>text2</subelement2>
    ...
    <additionalelement1>element1text</additionalelement1>
    <additionalelement2>element2text</additionalelement2>
    ...
</element>

The additional elements are stored in a dictionary, where the element name is the key. 附加元素存储在字典中,其中元素名称是键。

Is there a way to accomplish this with the XmlSerializer or any other serializer? 有没有办法使用XmlSerializer或任何其他序列化器来完成此任务?

I post this solution a lot : 我经常发布此解决方案:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication34
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            XElement element = doc.Descendants("element").FirstOrDefault();

            Dictionary<string,string> dict = element.Elements().GroupBy(x => x.Name.LocalName, y => (string)y)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
}

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

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