Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

Thursday, January 23, 2014

READING XML DOCUMENTS USING XDOCUMENT

READING XML DOCUMENTS USING XDOCUMENT

<employees>
    <department name="HR" >
        <employee ID="1" Name="Alex" passcode="100"/>
        <employee ID="2" Name="Anil" passcode="1545"/>
        <employee ID="3" Name="Vinod" passcode="856"/>
        <employee ID="4" Name="Sibi" passcode="1254"/>
    </department>
    <department name="Sales" >
        <employee ID="1" Name="Jeen" passcode="700"/>
        <employee ID="2" Name="Anil" passcode="545"/>
        <employee ID="3" Name="Kichu" passcode="86"/>
    </department>
</employees>



TO READ THE ABOVE XML USING XDOCUMENT OBJECT

Dim xdoc As XDocument = XDocument.Parse(<<xml string>>)
Dim deptList = From dl In xdoc.Descendants("department") Select dl

For Each dl In deptList
    '//PROCESS EACH DEPT.
    'ie dl="<department name="HR">

               <employee ID="1" Name="Alex" passcode="100"/>
               <employee ID="2" Name="Anil" passcode="1545"/>
               <employee ID="3" Name="Vinod" passcode="856" />
               <employee ID="4" Name="Sibi" passcode="1254" /> 
            </department>"

     'to read attributes use dl.Attribute("name").Value
 
     For Each em In dl.Elements("employee")
         '//PROCESS AN EMPLOYEE
         'ie em="<employee ID="1" Name="Alex" passcode="100" />"

     Next


Next


READING XML DOCUMENTS


READING XML DOCUMENTS

EXAMPLE-1

<?xml version="1.0" encoding="utf-16" standalone="yes"?>
     <generalsettings>
          <billheader>
                <title>Title Name</title>
                <phone> 0+91 xxxx xxxx</phone>
                <email> xxxxxx@xyz.com</email>
                <web address="hotelxyz.com"/>
          </billheader>
    </generalsettings>



To load the xml into an xml document object:

  Dim xmldoc As New XmlDocument
  xmldoc.LoadXml(<<xmlString>>)


To select a specific node from xml document:
     Dim titleNode As XmlNode = xmldoc.SelectSingleNode("/generalsettings/billheader/title")
     Dim titleText =   titleNode.InnerText


To read attribute values:
     Dim webNode As XmlNode = xmldoc.SelectSingleNode("/generalsettings/billheader/web ")
     Dim webAddress =   webNode.Attributes("address").Value




EXAMPLE-2

<?xml version="1.0" encoding="utf-16" standalone="yes"?>
<waiterList>
    <waiter ID="1" Name="Alex" passcode="100"/>
    <waiter ID="2" Name="Anil" passcode="1545"/>
    <waiter ID="3" Name="Vinod" passcode="856"/>
    <waiter ID="4" Name="Sibi" passcode="1254"/>
</waiterList>


To Read All Waiter Elements:
nodelist = doc.GetElementsByTagName("waiter")
For Each node As XmlElement In nodelist
   //process nodes//
Next