简体   繁体   中英

C# Parse XML to Object and store into Database

I'm currently working on an ASP.NET MVC 4.6 application using SQL Server 2014 as a data storage.

I need to parse a XML document from an URL, transform the XML into an object and store it into the database using Entity Framework 6.

I need to parse the XML from an URL like this:

http: //api.myserver.com/notes.xml

My XML looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<notes>
    <note>
      <to>Tove</to>
      <from>Jane</from>
      <heading>Reminder</heading>
      <body>Don't forget me this weekend!</body>
    </note>
    <note>
      <to>Doe</to>
      <from>John</from>
      <heading>Meeting</heading>
      <body>Hello Monday!</body>
    </note>
<notes>

My model class note looks like this:

public class Note
{
    public string To { get; set; }
    public string From { get; set; }
    public string Heading { get; set; }
    public string Body { get; set; }
}

My current test implementation looks like this, BUT I'm not so happy about the parsing of the XML:

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            String url = "https://www.w3schools.com/xml/note.xml";
            XmlDocument doc = new XmlDocument();
            doc.Load(url);
            XmlElement root = doc.DocumentElement;

            StringBuilder sb = new StringBuilder();
            sb.Append("<note>");

            foreach (XmlNode item in root)
            {
                sb.Append(item.OuterXml);
            }
            sb.Append("</note>");

            var result = Deserialize<Note>(sb.ToString());

            // further processing of result using EF 6

            Console.ReadKey();
        }


        public static T Deserialize<T>(string xmlText)
        {
            try
            {
                var stringReader = new StringReader(xmlText);
                var serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(stringReader);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }

    [XmlRoot(ElementName = "note", Namespace = "")]
    public class Note
    {
        [XmlElement("to")]
        public string To { get; set; }
        [XmlElement("from")]
        public string From { get; set; }
        [XmlElement("heading")]
        public string Heading { get; set; }
        [XmlElement("body")]
        public string Body { get; set; }
    }

}

As far as I noticed, .NET provides several approaches on how to parse XML:

  • XmlReader Class
  • XPath
  • XDocument
  • DataSet
  • LINQ

I was wondering, what would you use and how would u solve the parsing of the XML document from an URL using .NET and converting into an object to store it in a SQL Server DB?

Thanks for your help and consideration!!

This might help you, a serialize method and a Deserialize method.

public static string Serialize<T>(T dataToSerialize)
{
    try
    {
        var stringwriter = new ISOEncodingStringWriter();
        var serializer = new XmlSerializer(typeof(T));

        var xns = new XmlSerializerNamespaces();
        xns.Add(string.Empty, string.Empty);

        serializer.Serialize(stringwriter, dataToSerialize, xns);
        return stringwriter.ToString();
    }
    catch
    {
        throw;
    }
}

public static T Deserialize<T>(string xmlText)
{
    try
    {
        var stringReader = new System.IO.StringReader(xmlText);
        var serializer = new XmlSerializer(typeof(T));
        return (T)serializer.Deserialize(stringReader);
    }
    catch
    {
        throw;
    }
}

You use the method like this:

 Note result = Deserialize<Note>(xmlstring);

 Note note = new Note(){...};
 string convertedToXML = Serialize<Note>(note);

Just remember that you need to add some data to your note class so it can actually serialize the data:

[XmlRoot(ElementName = "root", Namespace = "")]
public class Note
{
    [XmlElementAttribute("To")]
    public string To { get; set; }

    [XmlElementAttribute("From")]
    public string From { get; set; }

    [XmlElementAttribute("Heading")]
    public string Heading { get; set; }

    [XmlElementAttribute("Body")]
    public string Body { get; set; }
}

I hope it helps :)

You can use LINQ to XML to traverse the nodes of your documents and either EF or ADO.NET to store them in the DB. You can start with this helpful tutorial: http://www.c-sharpcorner.com/UploadFile/de41d6/learning-linq-made-easy-tutorial-1/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM