VB.Net/XML LINQ/XElement — различия между версиями

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

Текущая версия на 12:45, 26 мая 2010

Add 5 new green Fords to the incoming document

  
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


Adding XElement to XElement

  
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


Add the new node to the bottom of the XML tree

  
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


After elements

  
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


Before elements

  
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


Build an XElement from string

  
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


Convert comma separated value to Xml

  

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


Create an in-memory XML document

  
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


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

  

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


Create a single XML element

  

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


Enumerate over the array to build an XElement

  
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


First Last Example

  

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


FirstLast Or Default Example

  
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


First name element has attributes

  
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


First name tag has child elements

  
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


FirstName tag"s parent has child elements

  
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


Get child elements by name directly

  
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


Get first descendant

  
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


Get value of each color using indexer

  
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


Is FirstName tag empty?

  
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


Is idperson tag empty?

  
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


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

  
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


Remove content from XElement

  
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


Remove from XElement

  
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


Remove the 4th Employee element.

  
 
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


Replace content from XElement

  
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


Set new value to Xml document

  
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


The Root property returns the top-level XElement

  
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


Update attribute for XElement

  
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


Update XElement

  
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


Using Ling query to create Xml output

  
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


using XElement.Parse to load Xml from String

  
Imports System
Imports System.Reflection
Imports System.Xml
Module Module1
    Sub Main()
        Dim doc As String = "<people>" & _
                     "<!-- Person section -->" & _
                         "<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


Using Xml Linq to output Html

  
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


Xml literal with function return

  
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


Xml Literal with string variable

  

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