Podmiana nazw elementów w XML'u podczas serializacji.

0

Część modelu w aplikacji musi być serializowana do różnych postaci xml'owych. Wymyśliłem że można by to zrobić na parę sposobów.

  1. XSLT.
  2. XmlWriter/XmlReader.
  3. XmlAttributeOverrides
  4. Duplikować część modelu

Trzecia opcja najbardziej do mnie przemawia. I wyglądało by to mniej więcej następująco:

using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace TestXml
{
   public class Person
   {
      public string FirstName { get; set; }
      public string LastName { get; set; }
   }

   internal class Program
   {
      private static void Main(string[] args)
      {
         // Nowe nazwy elementów...
         var nameAttributes = new XmlAttributes();
         nameAttributes.XmlElements.Add(new XmlElementAttribute
         {
            ElementName = "Name", 
            Type = typeof (string)
         });

         var surnameAttributes = new XmlAttributes();
         surnameAttributes.XmlElements.Add(new XmlElementAttribute
         {
            ElementName = "Surname", 
            Type = typeof (string)
         });

         // itd..

         var attrOverrides = new XmlAttributeOverrides();
         attrOverrides.Add(typeof (Person), "FirstName", nameAttributes);
         attrOverrides.Add(typeof (Person), "LastName", surnameAttributes);

         var person = new Person
         {
            FirstName = "Jan", 
            LastName = "Kowalski"
         };

         Console.WriteLine(XDocument.Parse(Serializer.ObjectToXml(person, attrOverrides)));
      }
   }

   public class Serializer
   {
      public static string ObjectToXml(object o, XmlAttributeOverrides xmlAttributeOverrides)
      {
         using (var stringWriter = new StringWriter())
         {
            using (var writer = XmlWriter.Create(stringWriter))
            {
               var ns = new XmlSerializerNamespaces();
               var xmlSerializer = new XmlSerializer(o.GetType(), xmlAttributeOverrides);
               xmlSerializer.Serialize(writer, o, ns);
            }
            return stringWriter.ToString();
         }
      }
   }
}

I teraz moje pytanie czy ktoś ma pomysł na jakiś inne rozwiązanie? Może ktoś robił coś podobnego.

0

Nie wiem czy będę Ci w stanie pomóc ale chciałbym lepiej zrozumieć do jakiś postaci, jakie będą różnice, czy np. struktura będzie taka sama tylko inne nazwy atrybutów czy w ogóle inne struktury.

0

Struktury są różne ale tylko elementy nadrzędne i tutaj nie ma problemu elementy podrzędne czyli te które nazwy chce zmieniać będą identyczne.

1 użytkowników online, w tym zalogowanych: 0, gości: 1