Deserialize xml to Linq to SQL object

I need to read in XML data sent from external systems that will be formatted like this:

<Applicant>
  <FirstName>John</FirstName>
  <LastName>Smith</LastName>
  <Address>12 Main St</Address>
</Applicant>

This is a direct mapping of my Linq to SQL Applicant class, with the exception of a few properties.

What is the best way to deserialize xml into a Linq to SQL object, so I can paste it directly into my database? I would also like to check the incoming XML and handle certain errors, if possible.

Thanks in advance!

+3
source share
3 answers

, , , ( ) - get/set.

, XmlSerializer, . , , , ( ).

, (XmlIgnore), .

using System;
using System.IO;
using System.Xml.Serialization;
public class Foo
{
    public int A { get; set; }
    public string B { get; set; }
    public int C { get; set; }
}
static class Program
{
    static readonly XmlSerializer serializer;
    static Program()
    {
        XmlAttributeOverrides or = new XmlAttributeOverrides();
        or.Add(typeof(Foo), "A", new XmlAttributes { // change to an attrib
            XmlAttribute = new XmlAttributeAttribute("tweaked")
        });
        or.Add(typeof(Foo), "B", new XmlAttributes {
            XmlIgnore = true // turn this one off
        });
        // leave C as a default named element
        serializer = new XmlSerializer(typeof(Foo), or);
    }
    static void Main()
    {
        Foo foo = new Foo { A = 123, B = "def", C = 456 }, clone;
        string xml;
        using (StringWriter sw = new StringWriter())
        {
            serializer.Serialize(sw, foo);
            xml = sw.ToString();
        }
        using (StringReader sr = new StringReader(xml)) {
            clone = (Foo)serializer.Deserialize(sr);
        }
        Console.WriteLine(xml);
        Console.WriteLine();
        Console.WriteLine(clone.A);
        Console.WriteLine(clone.B);
        Console.WriteLine(clone.C);
    }
}

, (, [XmlInclude]), partial class, LINQ-to-SQL; :

namespace My.Dal.Namespace {
    // add a type attribute to SomeEntity
    [XmlInclude(typeof(SomeDerivedEntity))]
    partial class SomeEntity { } 
}
+3

, XML- XML , xsd.exe Windows SDK, XML xsd (XML) .

, XML, , , , Applicant:

XmlSerializer ser = new XmlSerializer(typeof(Applicant));
StreamReader sr = new StreamReader(.....); // depends on where you get your XML from
Applicant result = (Applicant)ser.Deserialize(sr);

Applicant , XML - , ( ), (, INT - ).

0

It is much simpler.

First use a DataContractSerializer to serialize LinqToXml objects. This returns an array of bytes. With Encoding.UTF8.GetString (an array of bytes from the DataContractSerializer) you get an XML representation of your objects ...

Hope this helps

0
source

Source: https://habr.com/ru/post/1728831/


All Articles