0

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!!

1
  • 1
    Have you tried anything so far? Post some code. Commented Nov 13, 2017 at 9:25

2 Answers 2

2

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 :)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Troels! your sample code helped me a lot. I tried to implement it. I'm looking for a good way to transform the URL into a XML string... hmm
you want to add the url as a namespace?
1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.