A part of the XML looks like this.
<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?
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());
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.