How to parse XML which contains attributes and Element efficiently

Unanswered How to parse XML which contains attributes and Element efficiently

  • Monday, October 08, 2012 9:18 AM
     
     

    Dear all

    I have the following XML data snippets receive from a remote web service :

    What is the best way to read the Paragraph attribute and element in order to store them in my database table PARAGRAPH.

    Thnaks for advise
    regards

All Replies

  • Monday, October 08, 2012 2:43 PM
     
     

    Consider to tell us which .NET version you use, which programming language and which data from that XML exactly you want to store in a table which which fields exactly.

    Generally with .NET 3.5 and later there is LINQ to XML to work with XML e.g.

      XElement p = XElement.Parse(yourXmlStringSnippet);

      int id = (int)p.Attribute("id");

      int type = (int)p.Attribute("type");

      string name = (string)p.Element("name");

      string metDim = (string)p.Element("dimensions").Element("metric");

    If you want to use an API where you don't need to know XML then there is XML deserialization with System.Xml.Serialization.XmlSerializer, on the other hand it needs a schema (which you can generate from your sample) to then infer some .NET class code adorned with attributes which conrol the deserialization e.g.

     

    [XmlRoot]

    public class paragraph {

         [XmlAttribute] public int id { get; set; }

         [XmlAttribute] public int type { get; set; }

         public string name { get; set; }

         public string file { get; set }

         public dimensions { get; set; }

    }

    public class dimensions {

      public string metric { get; set; }

      public string imperial { get; set }

    }

    paragraph p;

    using (StringReader sr = new StringReader(yourXmlStringSnippet))

    {

      XmlSerializer ser = new XmlSerializer(typeof(paragraph));

      p = (paragraph)ser.Deserialize(sr);

    }


    MVP Data Platform Development My blog