locked
How to loop through XML to get the SQL and Mail Address RRS feed

  • Question

  • User-1355965324 posted

    I am trying to read an xml with the following format given below in C# . I have to store each sql Text and mailbody content and each email address under customer tag. Please help 

    <?xml version="1.0" encoding="utf-8" ?>
    <Queries>
    	<Customer>
    		<SQL ID="GYSQL">
    			Select * from customer where code ='GYSQL'
    		</SQL>
    		<Address>customer1@mail.com</Address>
        		<Address>customer2@mail.com</Address>
    	</Customer>
    	<Customer>
    		<SQL ID="TSSQL">
    			Select * from customer where code ='TSSQL'
    		</SQL>
    		<Address>customer3@mail.com</Address>
        		<Address>customer4@mail.com</Address>
    		<Address>customer5@mail.com</Address>
    	</Customer>
    </Queries>

    In my c# code

    string xml = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\Sql.xml";
    //Here I have to loop through each customer tag  and to get the SQLS and MailAddress from each corresponding tag  in a string variable
    While each Customer
    {
         string SQL =  ??
         string mailbody =  ??
         While Each Customer\MailAddress
         {
             string mailaddress = ??
         }
    
    }
    

    Thursday, December 3, 2020 9:45 AM

Answers

  • User-943250815 posted

    You have to use System.Xml.XmlDocument

        string myFile = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\Sql.xml";
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(myFile);
        XmlNodeList customerList = xmldoc.SelectNodes("Queries/Customer");
        foreach (XmlNode customer in customerList)
        {
          string sqlid = customer.SelectSingleNode("SQL").Attributes["ID"].Value;
          object sqlstr = customer.SelectSingleNode("SQL").InnerText;
          XmlNodeList addressList = customer.SelectNodes("Address");
          foreach (XmlNode address in addressList)
          {
            string email = address.InnerText;
          }
    
        }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, December 3, 2020 11:45 AM