VB.Net/XML LINQ/XElement

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

Add 5 new green Fords to the incoming document

<source lang="vbnet"> Module Program

 Sub Main()
   Dim doc As XElement = XElement.Load("Inventory.xml")
   For i As Integer = 0 To 4
     Dim newCar As New XElement("Car", _
       New XAttribute("ID", i + 1000), _
         New XElement("Color", "Green"), _
         New XElement("Make", "Ford"), _
         New XElement("PetName", ""))
     doc.Add(newCar)
   Next
   Console.WriteLine(doc)
 End Sub

End Module


 </source>


Adding XElement to XElement

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

   Sub Main()
       Dim xml As XElement = XElement.Load("People.xml")
       xml.AddFirst(New XElement("person", _
                       New XElement("id", 5), _
                       New XElement("firstname", "Tom"), _
                       New XElement("lastname", "Cruise"), _
                       New XElement("idrole", 1)))
       Console.WriteLine(xml)
   End Sub

End Module


 </source>


Add the new node to the bottom of the XML tree

<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>


After elements

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

   Sub Main()
       Dim xml As XElement = XElement.Load("People.xml")
       Dim firstName As XElement = xml.Descendants("firstname").First()
       Console.WriteLine("After <firstname>")
       For Each tag In firstName.ElementsAfterSelf()
           Console.WriteLine(tag.Name)
       Next
   End Sub

End Module


 </source>


Before elements

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

   Sub Main()
       Dim xml As XElement = XElement.Load("People.xml")
       Dim firstName As XElement = xml.Descendants("firstname").First()
       Console.WriteLine("Before <firstname>")
       For Each tag In firstName.ElementsBeforeSelf()
           Console.WriteLine(tag.Name)
       Next
   End Sub

End Module


 </source>


Build an XElement from string

<source lang="vbnet"> Class Car

 Public PetName As String
 Public ID As Integer

End Class Module Program

 Sub Main()
   Dim myElement As String = _
     "<Car ID="3">" & _
       "<Color>Yellow</Color>" & _
       "<Make>Yugo</Make>" & _
     "</Car>"
   Dim newElement As XElement = XElement.Parse(myElement)
   Console.WriteLine(newElement)
   Console.WriteLine()
   " Load the SimpleInventory.xml file.
   Dim myDoc As XDocument = XDocument.Load("SimpleInventory.xml")
   Console.WriteLine(myDoc)
 End Sub

End Module


 </source>


Convert comma separated value to Xml

<source lang="vbnet">

Imports System Imports System.Xml.Linq Imports Microsoft.VisualBasic.FileIO Imports System.Text Imports System.IO

   Public Class MainClass
       Public Shared Sub Main(ByVal args As String())
           Dim xmlTree As XElement
           Using parser As TextFieldParser = My.ruputer.FileSystem.OpenTextFieldParser("data.txt")
               parser.TextFieldType = FieldType.Delimited
               parser.Delimiters = New String() {","}
               parser.HasFieldsEnclosedInQuotes = True
               xmlTree = <Employees></Employees>
               Dim currentRow As String()
               Do While Not parser.EndOfData
                   currentRow = parser.ReadFields
                   xmlTree.Add(<Employee id=<%= currentRow(0) %>>
                                   <Name><%= currentRow(1) %></Name>
                                   <Title><%= currentRow(2) %></Title>
                                   <HireDate><%= currentRow(3) %></HireDate>
                                   <HourlyRate><%= currentRow(4) %></HourlyRate>
                               </Employee>)
               Loop
           End Using
           Console.WriteLine(xmlTree)
       End Sub
   End Class
  
   
 </source>


Create an in-memory XML document

<source lang="vbnet"> Class Car

 Public PetName As String
 Public ID As Integer

End Class Module Program

 Sub Main()
   ".
   Dim inventoryDoc As XDocument = _
     New XDocument( _
       New XDeclaration("1.0", "utf-8", "yes"), _
       New XComment("Current Inventory of AutoLot"), _
         New XElement("Inventory", _
           New XElement("Car", New XAttribute("ID", "1"), _
             New XElement("Color", "Green"), _
             New XElement("Make", "BMW"), _
             New XElement("PetName", "Stan") _
           ), _
           New XElement("Car", New XAttribute("ID", "2"), _
             New XElement("Color", "Pink"), _
             New XElement("Make", "Yugo"), _
             New XElement("PetName", "A") _
           ) _
         ) _
       )
   Console.WriteLine(inventoryDoc)
   inventoryDoc.Save("SimpleInventory.xml")
 End Sub

End Module


 </source>


Create a query to convert the xml data into fields delimited by quotes and commas.

<source lang="vbnet">

Imports System Imports System.Xml.Linq Imports Microsoft.VisualBasic.FileIO Imports System.Text Imports System.IO

   Public Class MainClass
       Public Shared Sub Main(ByVal args As String())
           Dim employees As XElement = XElement.Load("xmlFile.xml")
           Dim delimitedData As New StringBuilder
           Dim xmlData = _
               From emp In employees.<Employee> _
                   Select _
                   String.Format("""{0}"",""{1}"",""{2}"",""{3}"",""{4}""", _
                       emp.@id, emp.<Name>.Value, _
                       emp.<Title>.Value, emp.<HireDate>.Value, _
                       emp.<HourlyRate>.Value)
       End Sub
   End Class
  
   
 </source>


Create a single XML element

<source lang="vbnet">

Class Car

 Public PetName As String
 Public ID As Integer

End Class Module Program

 Sub Main()
   Dim inventory As XElement = _
   <Inventory>
     <Car ID="1">
       <Color>Green</Color>
       <Make>BMW</Make>
       <PetName>Stan</PetName>
     </Car>
   </Inventory>
   " Call ToString() on our XElement.
   Console.WriteLine(inventory)
 End Sub

End Module


 </source>


Enumerate over the array to build an XElement

<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 = _
         New XElement("Inventory", _
         From c In data _
           Select New XElement("Car", _
            New XAttribute("ID", c.ID), _
            New XElement("PetName", c.PetName) _
           ) _
         )
       Console.WriteLine(vehicles)
   End Sub

End Module


 </source>


First Last Example

<source lang="vbnet">

Imports System.Reflection Imports System

Public Class Role

   Public ID As Integer
   Public RoleDescription As String

End Class Public Class Person

   Public ID As Integer
   Public IDRole As Integer
   Public LastName As String
   Public FirstName As String

End Class Public Class Salary

   Public IDPerson As Integer
   Public Year As Integer
   Public SalaryYear As Double

End Class Module Module1

   Sub Main()
       Dim people As New List(Of Person)(New Person() { _
           New Person With {.ID = 1, .IDRole = 1, .LastName = "A", .FirstName = "Brad"}, _
           New Person With {.ID = 2, .IDRole = 2, .LastName = "G", .FirstName = "Tom"} _
       })
       Dim roles As New List(Of Role)(New Role() { _
           New Role With {.ID = 1, .RoleDescription = "Manager"}, _
           New Role With {.ID = 2, .RoleDescription = "Developer"} _
       })
       Dim salaries As New List(Of Salary)(New Salary() { _
               New Salary With {.IDPerson = 1, .Year = 2004, .SalaryYear = 10000.0}, _
               New Salary With {.IDPerson = 1, .Year = 2005, .SalaryYear = 15000.0}, _
               New Salary With {.IDPerson = 2, .Year = 2005, .SalaryYear = 15000.0} _
       })
       FirstLastExample()
   End Sub
   Function firstFunc(ByVal n As Integer) As Boolean
       Return (n Mod 2 = 0)
   End Function
   Function lastFunc(ByVal n As Integer) As Boolean
       Return (n Mod 2 = 0)
   End Function
   Public Sub FirstLastExample()
       Dim numbers As Integer() = New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9}
       Dim firstDelegate As New Func(Of Integer, Boolean)(AddressOf firstFunc)
       Dim lastDelegate As New Func(Of Integer, Boolean)(AddressOf lastFunc)
       Dim query = numbers.First()
       Console.WriteLine("The first element in the sequence")
       query = numbers.Last()
       Console.WriteLine("The last element in the sequence")
       Console.WriteLine("The first even element in the sequence")
       query = numbers.First(firstDelegate)
       Console.WriteLine("The last even element in the sequence")
       query = numbers.Last(lastDelegate)
   End Sub

End Module


 </source>


FirstLast Or Default Example

<source lang="vbnet"> Imports System.Reflection Imports System

Public Class Role

   Public ID As Integer
   Public RoleDescription As String

End Class Public Class Person

   Public ID As Integer
   Public IDRole As Integer
   Public LastName As String
   Public FirstName As String

End Class Public Class Salary

   Public IDPerson As Integer
   Public Year As Integer
   Public SalaryYear As Double

End Class Module Module1

   Sub Main()
       Dim people As New List(Of Person)(New Person() { _
           New Person With {.ID = 1, .IDRole = 1, .LastName = "A", .FirstName = "Brad"}, _
           New Person With {.ID = 2, .IDRole = 2, .LastName = "G", .FirstName = "Tom"} _
       })
       Dim roles As New List(Of Role)(New Role() { _
           New Role With {.ID = 1, .RoleDescription = "Manager"}, _
           New Role With {.ID = 2, .RoleDescription = "Developer"} _
       })
       Dim salaries As New List(Of Salary)(New Salary() { _
               New Salary With {.IDPerson = 1, .Year = 2004, .SalaryYear = 10000.0}, _
               New Salary With {.IDPerson = 1, .Year = 2005, .SalaryYear = 15000.0}, _
               New Salary With {.IDPerson = 2, .Year = 2005, .SalaryYear = 15000.0} _
       })
       FirstLastOrDefaultExample()
   End Sub
   Function firstFunc(ByVal n As Integer) As Boolean
       Return (n Mod 2 = 0)
   End Function
   Function lastFunc(ByVal n As Integer) As Boolean
       Return (n Mod 2 = 1)
   End Function
   Public Sub FirstLastOrDefaultExample()
       Dim numbers As Integer() = New Integer() {1, 3, 5, 7, 9}
       Dim firstDelegate As New Func(Of Integer, Boolean)(AddressOf firstFunc)
       Dim lastDelegate As New Func(Of Integer, Boolean)(AddressOf lastFunc)
       Dim query = numbers.FirstOrDefault(firstDelegate)
       Console.WriteLine("The first even element in the sequence")
       Console.WriteLine("The last odd element in the sequence")
       query = numbers.LastOrDefault(lastDelegate)
   End Sub

End Module


 </source>


First name element has attributes

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

   Sub Main()
       Dim xml As XElement = XElement.Load("People.xml")
       Dim firstName As XElement = xml.Descendants("firstname").First()
       Console.WriteLine("FirstName tag has attributes: {0}", firstName.HasAttributes)
   End Sub

End Module


 </source>


First name tag has child elements

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

   Sub Main()
       Dim xml As XElement = XElement.Load("People.xml")
       Dim firstName As XElement = xml.Descendants("firstname").First()
       Console.WriteLine("FirstName tag has child elements: {0}", firstName.HasElements)
   End Sub

End Module


 </source>


FirstName tag"s parent has child elements

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

   Sub Main()
       Dim xml As XElement = XElement.Load("People.xml")
       Dim firstName As XElement = xml.Descendants("firstname").First()
       Console.WriteLine("FirstName tag"s parent has child elements: {0}", firstName.Parent.HasElements)
   End Sub

End Module


 </source>


Get child elements by name directly

<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.Elements("person") _
           Where p.Element("id").value = 1 _
           Select p
       For Each record In query
           Console.WriteLine("Person: {0} {1}", _
                               record.Element("firstname"), _
                               record.Element("lastname"))
       Next
   End Sub

End Module


 </source>


Get first descendant

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

   Sub Main()
       Dim xml As XElement = XElement.Load("People.xml")
       Dim firstName As XElement = xml.Descendants("firstname").First()
       Console.WriteLine(firstName.Parent)
   End Sub

End Module


 </source>


Get value of each color using indexer

<source lang="vbnet"> Module Program

 Sub Main()
   Dim doc As XElement = XElement.Load("Inventory.xml")
   Dim ids = From c In doc.<Car> Select c.@carID
   For i As Integer = 0 To doc.Nodes.Count - 1
     Console.WriteLine(doc.<Car>(i).<Color>.Value)
   Next
 End Sub

End Module


 </source>


Is FirstName tag empty?

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

   Sub Main()
       Dim xml As XElement = XElement.Load("People.xml")
       Dim firstName As XElement = xml.Descendants("firstname").First()
       Console.WriteLine("Is FirstName tag empty? {0}", IIf(firstName.IsEmpty, "Yes", "No"))
   End Sub

End Module


 </source>


Is idperson tag empty?

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

   Sub Main()
       Dim xml As XElement = XElement.Load("People.xml")
       Dim idPerson As XElement = xml.Descendants("idperson").First()
       Console.WriteLine("Is idperson tag empty? {0}", IIf(idPerson.IsEmpty, "Yes", "No"))    
    End Sub

End Module


 </source>


Load the Employees.xml and store the contents into an XElement object.

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

   Public Class MainClass
       Public Shared Sub Main()
           Dim employees As XElement = XElement.Load("Employees.xml")
       End Sub
   End Class
  
   
 </source>


Remove content from XElement

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

   Sub Main()
       Dim xml As XElement = XElement.Load("People.xml")
       xml.Element("role").Remove()
       Console.WriteLine(xml)
   End Sub

End Module


 </source>


Remove from XElement

<source lang="vbnet"> Imports System Imports System.Data.DLinq Imports System.Expressions Imports System.Query Imports System.Reflection Imports System.Xml Module Module1

   Sub Main()
       Dim xml As XElement = XElement.Load("People.xml")
       xml.Descendants("idperson").First().Remove()
       xml.Elements("role").Remove()
       Console.WriteLine(xml)
   End Sub

End Module


 </source>


Remove the 4th Employee 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()
       End Sub
   End Class
  
   
 </source>


Replace content from XElement

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

   Sub Main()
       Dim xml As XElement = XElement.Load("People.xml")
       xml.Element("person").ReplaceNodes(New XElement("id", 5), _
                                            New XElement("firstname", "A"), _
                                            New XElement("lastname", "B"), _
                                            New XElement("role", 1))
       Console.WriteLine(xml)
   End Sub

End Module


 </source>


Set new value to Xml document

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

   Sub Main()
       Dim xdoc As XDocument = XDocument.Load("data.xml")
       xdoc.Element("PLAY").Element("PERSONA").SetValue("new value")
       Console.WriteLine(xdoc.Element("PLAY").Element("PERSONA").Value)
   End Sub

End Module


 </source>


The Root property returns the top-level XElement

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

   Public Class MainClass
       Public Shared Sub Main()
           Dim xmlDoc As XDocument = XDocument.Load("Employees.xml")
           Console.WriteLine("The document declaration is "{0}"", xmlDoc.Declaration.ToString)
           Console.WriteLine("The root element is "{0}"", xmlDoc.Root.Name.LocalName)
       End Sub
   End Class
  
   
 </source>


Update attribute for XElement

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

   Sub Main()
       Dim xml As XElement = XElement.Load("People.xml")
       Dim role As XElement = xml.Descendants("id").First()
       Console.WriteLine(role)
       role.SetAttributeValue("year", "2006")
       Console.WriteLine(role)
   End Sub

End Module


 </source>


Update XElement

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

   Sub Main()
       Dim xml As XElement = XElement.Load("People.xml")
       Dim role As XElement = xml.Descendants("role").First()
       Console.WriteLine(role)
       role.SetElementValue("description", "Actor")
       Console.WriteLine(role)
   End Sub

End Module


 </source>


Using Ling query to create Xml output

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

       Public Class Employee
           Public EmployeeID As Integer
           Public FirstName As String
           Public LastName As String
           Public Title As String
           Public HireDate As DateTime
           Public HourlyWage As Double
       End Class
   Public Class MainClass
       Public Shared Sub Main()
           Dim employeeList = New Employee() _
                   {New Employee With {.EmployeeID = 1, _
                                      .FirstName = "A", _
                                      .LastName = "M", _
                                      .Title = "Tester", _
                                      .HireDate = DateTime.Now, _
                                      .HourlyWage = 10.0}, _
                   New Employee With {.EmployeeID = 2, _
                                      .FirstName = "B", _
                                      .LastName = "C", _
                                      .Title = "Tester", _
                                      .HireDate = DateTime.Now, _
                                      .HourlyWage = 10.75}}
           Dim employees = <Employees>
                   <%= From emp In employeeList _
                       Select _
                       <Employee id=<%= emp.EmployeeID %>>
                           <Name><%= emp.FirstName & " " & emp.LastName %></Name>
                           <Title><%= emp.Title %></Title>
                           <HireDate><%= emp.HireDate.ToString("MM/dd/yyyy") %></HireDate>
                           <HourlyRate><%= emp.HourlyWage %></HourlyRate>
                       </Employee> _
                   %>
               </Employees>

           employees.Save("Employees.xml")
           Console.WriteLine(employees.ToString())
       End Sub
   End Class
  
   
 </source>


using XElement.Parse to load Xml from String

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

   Sub Main()
       Dim doc As String = "<people>" & _
                    "" & _
                        "<person>" & _
                         "<id>1</id>" & _
                         "<firstname>A</firstname>" & _
                         "<lastname>B</lastname>" & _
                         "<idrole>1</idrole>" & _
                        "</person>" & _
                          "</people>"
       Dim xml As XElement = XElement.Parse(doc)
       Console.WriteLine(xml)
   End Sub

End Module


 </source>


Using Xml Linq to output Html

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

   Sub Main()
       Dim xml As XElement = XElement.Load("People.xml")
       Dim html As New XElement("HTML", _
                               New XElement("BODY", _
                                   New XElement("TABLE", _
                                       New XElement("TH", "ID"), _
                                       New XElement("TH", "Full Name"), _
                                       New XElement("TH", "Role"), _
           From p In xml.Descendants("person"), r In xml.Descendants("role") _
           Where p.Element("idrole").Value = r.Element("id").Value _
           Select New XElement("TR", _
                                       New XElement("TD", p.Element("id").Value), _
                                       New XElement("TD", p.Element("firstname").Value _
                                       & " " & p.Element("lastname").Value), _
                                       New XElement("TD", r.Element("roledescription").Value)))))
       html.Save("People.html")
   End Sub

End Module


 </source>


Xml literal with function return

<source lang="vbnet"> Module Program

 Sub Main()
   Dim interiorColor As String = "White"
   Dim exteriorColor As String = "Blue"
   Dim car1 As XElement = _
 <Automobile>
   <petname><%= GetPetName() %></petname>
   <color type="interior"><%= interiorColor %></color>
   <color type="exterior"><%= exteriorColor %></color>
 </Automobile>
   Console.WriteLine(car1)
 End Sub
 Function GetPetName() As String
   Return "Sidd"
 End Function

End Module


 </source>


Xml Literal with string variable

<source lang="vbnet">

Module Program

 Sub Main()
   Dim interiorColor As String = "White"
   Dim exteriorColor As String = "Blue"
   Dim car1 As XElement = _
 <Automobile>
   <petname><%= GetPetName() %></petname>
   <color type="interior"><%= interiorColor %></color>
   <color type="exterior"><%= exteriorColor %></color>
 </Automobile>
   Console.WriteLine(car1)
 End Sub
 Function GetPetName() As String
   Return "Sidd"
 End Function

End Module


 </source>