VB.Net/XML LINQ/Query

Материал из VB Эксперт
Перейти к: навигация, поиск

Build an element with a query

<source lang="vbnet"> Imports System.Collections.Generic Class Car

 Public PetName As String
 Public ID As Integer

End Class Module Program

 Sub Main()
   Dim data As New List(Of Car)
   data.Add(New Car With {.PetName = "A", .ID = 10})
   data.Add(New Car With {.PetName = "Pat", .ID = 11})
   data.Add(New Car With {.PetName = "Danny", .ID = 12})
   data.Add(New Car With {.PetName = "B", .ID = 13})
   Dim vehicles As XElement = _
     <Inventory>
       <%= From c In data _
         Select <Car ID=<%= c.ID %>>
                  <PetName><%= c.PetName %></PetName>
                </Car> %>
     </Inventory>
   Console.WriteLine(vehicles)
 End Sub

End Module


 </source>


Build a query to join the two XML trees on the employee"s Id.

<source lang="vbnet"> Imports System Imports System.Xml.Linq

   Public Class MainClass
       Public Shared Sub Main()
           Dim employees As XElement = XElement.Load("Employees.xml")
           Dim titles As XElement = XElement.Load("Titles.xml")
           Dim query = From emp In employees.<Employee> _
                       Group Join title In titles.<Title> _
                       On emp.@id Equals title.@empId _
                       Into TitleList = Group _
                       Select EmployeeName = emp.<Name>.Value, _
                              TitleList
           For Each emp In query
               Console.WriteLine(emp.EmployeeName)
               For Each title In emp.TitleList
                   Console.WriteLine("{0} - {1}", title.<Name>.Value, title.<Status>.Value)
               Next
           Next
       End Sub
   End Class
  
   
 </source>


Creating new Xml element in the query

<source lang="vbnet"> Imports System Imports System.Reflection Imports System.Xml Module Module1

   Sub Main()
       Dim xml As XElement = XElement.Load("People.xml")
       Dim query = From p In xml.Descendants("person"), s In xml.Descendants("id") _
           Where p.Element("id").Value = s.Attribute("id").Value _
           Select New With {.FirstName = p.Element("firstname").Value, _
                               .LastName = p.Element("lastname").Value, _
                               .Amount = s.Attribute("salar").Value}
       For Each record In query
           Console.WriteLine("Person: {0} {1}, Salary {2}", record.FirstName, _
                                                           record.LastName, _
                                                           record.Amount)
       Next
   End Sub

End Module


 </source>


Display the employee names and their hourly rate

<source lang="vbnet"> Imports System Imports System.Xml.Linq

   Public Class MainClass
       Public Shared Sub Main()
           Dim employees As XElement = XElement.Load("Employees.xml")
           Dim beforeQuery = From ele In employees.<Employee> Select Name = ele.<Name>.Value, Wage = CDbl(ele.<HourlyRate>.Value)
           For Each ele In beforeQuery
               Console.WriteLine("{0} gets paid ${1} an hour.", ele.Name, ele.Wage.ToString())
           Next
       End Sub
   End Class
  
   
 </source>


Display the employee names and their new hourly rate.

<source lang="vbnet"> Imports System Imports System.Xml.Linq

   Public Class MainClass
       Public Shared Sub Main()
           Dim employees As XElement = XElement.Load("Employees.xml")
           Dim afterQuery = From ele In employees.<Employee> Select Name = ele.<Name>.Value, Wage = CDbl(ele.<HourlyRate>.Value)
           For Each ele In afterQuery
               Console.WriteLine("{0} gets paid ${1} an hour.", ele.Name, ele.Wage.ToString("##.##"))
           Next
       End Sub
   End Class
  
   
 </source>


Execute the query and loop through the results, displaying the Information to the screen.

<source lang="vbnet"> Imports System Imports System.Xml.Linq Imports System.Xml.XPath

   Public Class MainClass
       Public Shared Sub Main()
           Dim employees As XElement = XElement.Load("EmployeesAndTasks.xml")
           Dim linqQuery = From task In employees.<Employee>...<Task> _
                           Select EmployeeName = task.Parent.Parent.<Name>.Value, _
                                  TaskName = task.<Name>.Value, _
                                  task.<Description>.Value _
                           Order By EmployeeName
           For Each task In linqQuery
               Console.WriteLine("{0,-15} - {1} ({2})", task.EmployeeName, task.TaskName, task.Description)
           Next
       End Sub
   End Class
  
   
 </source>


Loop through all of the Employee elements and remove the HireDate element.

<source lang="vbnet">

Imports System Imports System.Xml.Linq

   Public Class MainClass
       Public Shared Sub Main()
           Dim employees As XElement = XElement.Load("Employees.xml")
           employees.<Employee>.ElementAt(3).Remove()
           For Each ele In employees.<Employee>.ToList
               ele.SetElementValue("HireDate", Nothing)
           Next
           Console.WriteLine(employees.ToString)
       End Sub
   End Class
  
   
 </source>


Loop through all the Employee nodes and insert the new "TerminationDate" node and the "Status" attribute

<source lang="vbnet"> Imports System Imports System.Xml.Linq

   Public Class MainClass
       Public Shared Sub Main()
           Dim employees As XElement = XElement.Load("Employees.xml")
           Dim newEmployee = <Employee id=<%= 1 %>>
                                 <Name>First</Name>
                                 <Title>Coder</Title>
                                 <HireDate>07/15/2006</HireDate>
                                 <HourlyRate>9.95</HourlyRate>
                             </Employee>
           employees.Add(newEmployee)
           For Each ele In employees.<Employee>
               ele.Add(<TerminationDate></TerminationDate>)
               ele.Add(New XAttribute("Status", ""))
           Next
           Console.WriteLine(employees.ToString())
       End Sub
   End Class
  
   
 </source>


Loop through all the HourlyRate elements, setting them to the new payrate, which is the old rate * 5%.

<source lang="vbnet"> Imports System Imports System.Xml.Linq

   Public Class MainClass
       Public Shared Sub Main()
           Dim employees As XElement = XElement.Load("Employees.xml")
           Dim beforeQuery = From ele In employees.<Employee> Select Name = ele.<Name>.Value, Wage = CDbl(ele.<HourlyRate>.Value)
           Dim currentPayRate As Double = 0
           For Each ele In employees.<Employee>.<HourlyRate>
               currentPayRate = (ele.Value) + ((ele.Value) * 0.05)
               ele.SetValue(currentPayRate)
           Next
       End Sub
   End Class
  
   
 </source>


Loop through a node in Xml document

<source lang="vbnet"> Module Program

 Sub Main()
   Dim doc As XElement = XElement.Load("Inventory.xml")
   Dim petNames = From pn In doc...<PetName> Select pn.Value
   For Each name In petNames
     Console.WriteLine("Name: {0}", name)
   Next
 End Sub

End Module


 </source>


Query for all of the employees that make (HourlyRate) more than $100 an hour

<source lang="vbnet"> Imports System Imports System.Xml.Linq

   Public Class MainClass
       Public Shared Sub Main()
           Dim employees As XElement = XElement.Load("Employees.xml")
           Dim query = From ele In employees.<Employee> _
                       Where CDbl(ele.<HourlyRate>.Value) >= 100 _
                       Select ele.@id, ele.<Name>.Value, Pay = CDbl(ele.<HourlyRate>.Value) _
                       Order By Name
           For Each emp In query
               Console.WriteLine("[{0,-2}] {1,-25} ${2,-6}", emp.id, emp.Name, emp.Pay.ToString("##.00"))
           Next
       End Sub
   End Class
  
   
 </source>


Query the XML Tree and get the Name and Hourly Rate elements.

<source lang="vbnet"> Imports System Imports System.Xml.Linq

   Public Class MainClass
       Public Shared Sub Main()
           Dim employees As XElement = XElement.Load("Employees.xml")
           Dim afterQuery = From ele In employees.<Employee> Select Name = ele.<Name>.Value, Wage = CDbl(ele.<HourlyRate>.Value)
       End Sub
   End Class
  
   
 </source>


Query Xml document by Node value

<source lang="vbnet">

Module Program

 Sub Main()
   Dim doc As XElement = XElement.Load("Inventory.xml")
   Dim fords = From c In doc...<Make> Where c.Value = "Ford" Select c
   For Each f In fords
     Console.WriteLine("Make: {0}", f)
   Next
 End Sub

End Module


 </source>


Use LINQ to get the tasks for each employee and order them by the employee"s name.

<source lang="vbnet"> Imports System Imports System.Xml.Linq Imports System.Xml.XPath

   Public Class MainClass
       Public Shared Sub Main()
           Dim employees As XElement = XElement.Load("EmployeesAndTasks.xml")
           Dim linqQuery = From task In employees.<Employee>...<Task> _
                           Select EmployeeName = task.Parent.Parent.<Name>.Value, _
                                  TaskName = task.<Name>.Value, _
                                  task.<Description>.Value _
                           Order By EmployeeName
       End Sub
   End Class
  
   
 </source>


Using For Each to loop through the result of Xml query

<source lang="vbnet"> Imports System Imports System.Reflection Imports System.Xml Module Module1

   Sub Main()
       Dim xml As XElement = XElement.Load("People.xml")
       Dim query = From s In xml.Elements("salary").Elements("id") _
           Where s.Attribute("year").Value = 2004 _
           Select s
       For Each record In query
           Console.WriteLine("Amount: {0}", record.Attribute("salaryyear"))
       Next
   End Sub

End Module


 </source>