XmlSerializer List Item Element Name, Value

Markus Freitag 3,786 Reputation points


I need this one.

		<NAME value="Receiver Serial number" />  
    	<QUANTITY value="67" />  
		<PRICE value="63 €" />  

I got this.

    <KeyValue value="Receiver Serial number">  
    <KeyValue value="67">  

What is wrong, how can I solve it well?

That is my code!

public class HelperTest  
        private static readonly XmlWriterSettings WriterSettingsExclusiv = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true, Encoding = new UTF8Encoding(true) };  
        private static readonly XmlSerializerNamespaces Namespaces = new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", ""), });        
        public Group Group { get; set; }  
        public  void SaveTraceXML<T>(string file, T dataObject)  
            XmlSerializer serializer = new XmlSerializer(typeof(T));  
            using (Stream stream = new FileStream(file, FileMode.Create))  
            using (XmlWriter xmlWriter = XmlWriter.Create(stream, WriterSettingsExclusiv))  
                serializer.Serialize(xmlWriter, dataObject, Namespaces);  
    public class KeyValue  
        public string Key { get; set; }  
        public string Value { get; set; }  
    public  class Group  
        //public Dictionary<string, KeyValue> Task { get; set; }  
        public List<KeyValue> ListTaskElements { get; set; }  
        // public SerializableDictionary<string, KeyValue> Task2 { get; set; }  
// *** from Main Window!  
HelperTest ht = new HelperTest();  
ht.Group = new Group();  
ht.Group.ListTaskElements = new System.Collections.Generic.List<KeyValue>();  
ht.Group.ListTaskElements.Add(new KeyValue() { Key = "Name", Value = "Receiver Serial number" });  
ht.Group.ListTaskElements.Add(new KeyValue() { Key = "Quantiy", Value = "67" });  
ht.SaveTraceXML(@"C:\Temp\TTTTTT.XML", ht.Group);  

Thanks for your help in advance!

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,395 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 24,311 Reputation points Microsoft Vendor

    @Markus Freitag , after my attempt, I find it is hard to get your desired output if you want to Serialize your class into a file at once.

    I recommend that you make some changes in the generated file.

    Here is a code example you could refer to.

        var doc = XDocument.Load("test.XML");  
            var result = doc.Descendants("KeyValue");  
            foreach (var item in result)  
                item.Name = item.Element("Key").Value;  



    Hope this could help you.

    Best Regards,

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful