Translate

Tuesday 1 April 2014

Read XML Value using html Agility pack, linq in c#

  private void getxmlvalue()
    {

        string[] xmlpath = Directory.GetFiles(fileLocation + "XML" + "/" );
        string id= string.Empty,  FileName = string.Empty, Extension = string.Empty,
        Authorname = string.Empty;;
        for (int i = 0; i <= xmlpath.Length - 1; i++)
        {
            FileInfo file = new FileInfo(xmlpath[i]);
            FileName = file.Name;
            Extension = file.Extension;
            if (Extension == ".xml")
            {
                StreamReader str = new StreamReader(xmlpath[i]);
                string strLings = str.ReadToEnd();
                str.Close();
                HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
                htmlDoc.OptionFixNestedTags = true;
                htmlDoc.LoadHtml(strLings);
                if (htmlDoc.DocumentNode != null)
                {
                    try
                    {
                        if (strLings.Contains("id"))
                        {
                            foreach (HtmlNode nodepage in htmlDoc.DocumentNode.SelectNodes("//id"))
                            {
                                if (nodepage != null)
                                {
                                    id = nodepage.InnerHtml.Trim();
                                }
                            }
                        }
                        if (strLings.Contains("authername"))
                        {
                            foreach (HtmlNode nodepage in htmlDoc.DocumentNode.SelectNodes("//authername"))
                            {
                                if (nodepage != null)
                                {
                                    string lang = nodepage.GetAttributeValue("lang", "");
                                    if (lang == "EN")
                                    {
                                        Authorname += nodepage.InnerText.ToString() + "|";
                                    }
                                }
                                //  Authorname = Authorname.Remove(Authorname.LastIndexOf(";"), 1);
                            }
                        }
                       //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Read XML value from nested parent node and child node element

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (strLings.Contains("body"))
                        {
                            if (strLings.Contains("book-part"))
                            {
                                foreach (HtmlNode node1 in htmlDoc.DocumentNode.SelectNodes("//book-part"))
                                {
                                    strBook_ID = node1.GetAttributeValue("id", "");

                                    HtmlNode node2 = node1.SelectSingleNode(".//title");
                                    if (node2 != null)
                                        strTitle = node2.InnerHtml;

                                    HtmlNode node3 = node1.SelectSingleNode(".//volume-id"); // take current value
                                    if (node3 != null)
                                        strDOI = node3.InnerHtml;

                                  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                        DataRow dr = dtup.NewRow();
                        // Add value to datatable
                        dtup.Rows.Add(dr);            
                        id = "";                      
                        Authorname = "";
                     
                    }
                    catch (Exception ex)
                    {
                      ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "", "alert('Error Occur in getting value from XML File');", true);
                    }
                    finally
                    {
                    }
                }
            }
        }
       // save the value to database using table value parameter
    }

--------------------------------------------------------------------------------------------------

using LINQ :


<University>
  <School SchoolId="1" SchoolName="Languages">
    <Subjects>
      <Subject Id="1" SubjectName="English"/>
      <Subject Id="2" SubjectName="French"/>
      <Subject Id="3" SubjectName="Italian"/>
      <Subject Id="4" SubjectName="Spanish"/>
    </Subjects>
  </School>
  <School SchoolId="2" SchoolName="Sciences">
    <Subjects>
      <Subject Id="1" SubjectName="Biology"/>
      <Subject Id="2" SubjectName="Physics"/>
    </Subjects>
  </School>
</University>
Solution:
string fileLocation = WebConfigurationManager.AppSettings["FileUPDN"].ToString();
        string xmlpath = fileLocation + "XML" + "/" + Convert.ToString(txtxmlname.Text)
        XmlReader reader = XmlReader.Create(xmlpath[i]);
        XElement el = XElement.Load(reader);
        reader.Close();
            var items_list = from item in el.Elements("University").Descendants()
                            where (item.Name == "School")
                            select item;
        foreach (var node in items_list)
            {
                schoolId = (int)node .Attribute("SchoolId");
                schoolName = (string)node .Attribute("SchoolName");
                subjects = from subject in node .Element("Subjects").Elements("Subject")
                                       select (string)subject.Attribute("SubjectName");
            }