0

I am using XmlSerializer and I want to achieve XML tree:

<request>
   <ix>ID</ix>
      <content>
            <name>NAMEVALUE</name>
            <visits>INT</visits>
         <dateRequested>yyyy-MM-dd</dateRequested>
      </content>
</request>

with model:

[XmlRoot(ElementName = "request")]
    public class RequestModel
    {
        [XmlElement("ix")]
        [JsonProperty("ix")]
        public int ID { get; set; }
        [XmlElement("name")]
        [JsonProperty("name")]
        public string Name { get; set; }
        [XmlElement("visits")]
        [JsonProperty("visits")]
        public int? Visits { get; set; }
        [XmlElement("date")]
        [JsonProperty("date")]
        public DateTime Date { get; set; }
    }

What attribute should I use to receive <content> group in the XMl tree?

My serializer:

IEnumerable<RequestJSONModel> getModels = _context.Requests.ToList();
            foreach (var item in getModels)
            {
                RequestModel requestModel = new RequestModel();
                Content contentModel = new Content();
                //serialize
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(RequestModel));
                var serializedItem = "";
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", "");
                using (StringWriter writer = new Utf8StringWriter())
                {
                    xmlSerializer.Serialize(writer, xmlModel, ns);
                    serializedItem = writer.ToString(); // Your XML
                }
                serializedItem = serializedItem.Replace("\r\n", string.Empty);
            }

How can I parse public class RequestModel and public class Content if I use jdweng's solution?

  • you can try object inside object :: `RequestModel->{public ContentModel model{get;set;}{` – לבני מלכה Dec 16 '18 at 11:30
  • 1
    Not related to your question, but your use of [`Utf8StringWriter`](https://stackoverflow.com/a/3862106/11683) is completely pointless because after `serializedItem = writer.ToString()` your serialized data is [back to UTF-16](https://stackoverflow.com/a/3862232/11683). – GSerg Dec 16 '18 at 19:02
  • @GSerg replacing with `.ToArray()` should be enough? –  Dec 16 '18 at 19:12
  • A `StringWriter` does not define a `ToArray()`. In all cases all `string`s are always UTF-16. – GSerg Dec 16 '18 at 19:24
  • @GSerg later on I need to create XML document with `XmlDocument xmlFile = new XmlDocument(); xmlFile.LoadXml(serializedItem);` and as far as I know it gives me a string anyway. Is it possible to encode it at the end with this solution? https://stackoverflow.com/questions/14057434/how-can-i-transform-string-to-utf-8-in-c like that: `byte[] bytes = Encoding.Default.GetBytes(serializedItem); serializedItem = Encoding.UTF8.GetString(bytes);` ? –  Dec 16 '18 at 19:27
  • No, `serializedItem` will still be a `string` which is always UTF-16, but if you ultimately want to feed that string to `LoadXml`, then why are you trying to make it UTF-8? That would only make sense if you wanted to save the persisted version somewhere. – GSerg Dec 16 '18 at 19:37
  • beacuse later I am saving the file in applications path `string savePath = Path.Combine("App_Data", "xml", xmlModel.Date); xmlFile.Save(savePath);` –  Dec 16 '18 at 19:39
  • @GSerg by the way, I tryed with Notapad++ encoding detection of the file and it shows me UTF-8-BOM, because of some reason, even after removing the header... –  Dec 16 '18 at 19:51
  • That is because `XmlDocument` preserves the [encoding specified in the XML header](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmldocument.save?view=netframework-4.7.2#System_Xml_XmlDocument_Save_System_String_) (`XmlDeclaration.Encoding`), and you have UTF-8 specified in the XML header, so that is what you get when you save it to file, even though the string from which you created the `XmlDocument` instance was in UTF-16 (and could not be in anything else). – GSerg Dec 16 '18 at 20:48
  • @GSerg I was thinking about the same, and before importing the file to Notepad++ I was removing header from the file. After this action, the file was still recognised as a `UTF-8-BOM` –  Dec 16 '18 at 21:25

1 Answers1

0

try this

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

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            RequestModel model = new RequestModel() {
                ix = 123,
                content = new Content() {
                    Name = "NAMEVALUE",
                    Visits = 456,
                    dateRequested = "2018-12-16"
                }
            };

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            XmlWriter writer = XmlWriter.Create(FILENAME, settings);

            XmlSerializer serializer = new XmlSerializer(typeof(RequestModel));

            serializer.Serialize(writer, model);
        }
    }
    [XmlRoot(ElementName = "request")]
    public class RequestModel
    {
        [XmlElement("ix")]
        public int ix { get; set; }

        [XmlElement("content")]
        public Content content { get; set; }

    }
    [XmlRoot(ElementName = "content")]
    public class Content
    {
        [XmlElement("name")]
        public string Name { get; set; }
        [XmlElement("visits")]
        public int? Visits { get; set; }

        private DateTime Date { get; set; }

        [XmlElement("dateRequested")]
        public string dateRequested
        {
            get { return Date.ToString("yyyy-MM-dd"); }
            set { Date = DateTime.ParseExact(value, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); }
        }

    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • I updated my question with my serializer and now I have no idea yet how to use your solution to serialize it. –  Dec 16 '18 at 18:13
  • Ok, this was great! Where can I ship you some pack chocolates? I belive that you saved me loads of my time trying out various ideas :) I already spend half day trying to figure out solution. –  Dec 16 '18 at 21:43