Udostępnij za pośrednictwem


Jak sformatować wartości DateTime i Date w kodzie XML wyodrębnionym z zestawu danych ADO.NET przy użyciu programu Visual Basic .NET

W tym artykule opisano sposób formatowania DateTime i Date wartości DataTable kolumn w formacie XML wyodrębnionym z obiektu ADO.NET DataSet .

Oryginalna wersja produktu: Visual Basic .NET
Oryginalny numer KB: 811767

Podsumowanie

W ADO.NET DateTime wartości DataTable i Date kolumn są zapisywane w formacie XSDDateTime, Date gdy DataSet element jest zapisywany jako XML. Standardowe XSD DateTime i Date formaty są CCYY-MM-DDThh:mm:ss i CCYY-MM-DD, odpowiednio, ponieważ bazowy schemat DataSet XSD mapuje DateTime i kolumny bazy danych na DateTime typy danych i Date XSDDate.

Aby wygenerować kod XML, w którym DateTime wartości i Date są reprezentowane w wymaganych formatach niestandardowych, użyj jednej z następujących metod.

Metoda 1. Używanie klasy XmlConvert

  1. Otwórz program Microsoft Visual Studio .NET. W programie Visual Basic .NET utwórz nowy projekt aplikacji internetowej ASP.NET o nazwie DateTimeXmlConvert.

  2. Kliknij prawym przyciskiem myszy powierzchnię projektanta WebForm1.aspx, a następnie kliknij polecenie Wyświetl kod.

  3. Dodaj następujący kod na końcu Imports sekcji dyrektyw w WebForm1.aspx.vb:

    Imports System.Xml
    Imports System.Text
    Imports System.Data.SqlClient
    
  4. Wklej następujący kod w Page_Load zdarzeniu:

    ' Change SqlServerName, UserId and Password in the following connection string.
    Dim conn As String = "Server=<SQLServerName>; database=Northwind; user id=<UserID>; password=<Password>;"
    Dim connection As SqlConnection = New SqlConnection()
    connection.ConnectionString = conn
    
    Dim objDataSet As DataSet = New DataSet()
    Dim objAdapter As SqlDataAdapter = New SqlDataAdapter()
    Dim objCmd As SqlCommand = New SqlCommand()' Retrieve the first 10 records from the employees table.
    objCmd.CommandText = "select top 10 FirstName,BirthDate from employees"
    objCmd.Connection = connection
    objAdapter.SelectCommand = objCmd
    objAdapter.Fill(objDataSet)
    
    connection.Close()' Create an instance of XmlTextReader class that reads the XML data.
    Dim xmlReader As XmlTextReader = New XmlTextReader(objDataSet.GetXml(),XmlNodeType.Element,Nothing)
    
    Response.ContentType = "text/xml"
    Dim xmlWriter As XmlTextWriter = New XmlTextWriter(Response.OutputStream,Encoding.UTF8)
    xmlWriter.Indentation = 4
    xmlWriter.WriteStartDocument()
    Dim elementName As String = ""
    
    ' Parse & display each node
    While xmlReader.Read()
        Select Case xmlReader.NodeType
            Case XmlNodeType.Element
                xmlWriter.WriteStartElement(xmlReader.Name)
                elementName = xmlReader.Name
    
            Case XmlNodeType.Text
                If elementName.ToLower() = "birthdate" Then
                    xmlWriter.WriteString(XmlConvert.ToDateTime(xmlReader.Value).ToString())
                Else
                    xmlWriter.WriteString(xmlReader.Value)
                End If
    
            Case XmlNodeType.EndElement
                xmlWriter.WriteEndElement()
        End Select
    End While
    xmlWriter.Close()
    
  5. Zapisz zmiany w WebForm1.aspx.vb.

  6. W menu Kompilacja kliknij pozycję Kompiluj rozwiązanie.

  7. Uruchom program Microsoft Internet Explorer i otwórz WebForm1.aspx, określając http://IISServerName/DateTimeXmlConvert/WebForm1.aspx adres URL, pod którym IISServerName jest nazwą serwera usług Microsoft Internet Information Services (IIS).

Teraz możesz zobaczyć, że plik XML renderowany w przeglądarce jest wyświetlany w formacie niestandardowym DateTime .

Metoda 2. Stosowanie przekształcenia XSLT w reprezentacji XML danych Zestawu danych

Do implementowania niestandardowych procedur można użyć wbudowanych bloków skryptów i składników kodu zewnętrznego, znanych jako obiekty rozszerzenia XSLT. Są one wywoływane podczas XSLT w celu wykonywania obliczeń i przetwarzania danych. Firma Microsoft zaleca unikanie używania wbudowanych bloków skryptów. Obiekty rozszerzeń umożliwiają implementowanie niestandardowych procedur podczas projektowania przenośnych arkuszy stylów XSLT.

Tworzenie formularza internetowego ASP.NET

  1. Utwórz nowy projekt aplikacji internetowej platformy .NET w języku Visual Basic ASP.NET o nazwie DateTimeXSLT.

  2. Dodaj nową klasę o nazwie DateConvertor.vb do projektu.

  3. Zastąp istniejący kod następującym kodem w DateConvertor klasie:

    Public Class DateConvertor
        Public Function GetDateTime(ByVal data As String, ByVal format As String) As String
            Dim dt As DateTime = DateTime.Parse(data)
            Return dt.ToString(format)
        End Function
    End Class
    
  4. Zapisz zmiany w DateConvertor.vb.

  5. Kliknij prawym przyciskiem myszy powierzchnię projektanta WebForm1.aspx, a następnie kliknij polecenie Wyświetl kod.

  6. Dodaj następujący kod na końcu Imports sekcji dyrektyw w WebForm1.aspx.vb:

    Imports System.IO
    Imports System.Xml
    Imports System.Xml.Xsl
    Imports System.Xml.XPath
    Imports System.Data.SqlClient
    
  7. Wklej następujący kod w Page_Load zdarzeniu:

    ' Change SqlServerName, UserId and Password in the following connection string.
    Dim strConn As String = "Server=<SQLServerName>; database=Northwind; user id=<UserID>; password=<Password>;"
    Dim connection As SqlConnection = New SqlConnection()
    connection.ConnectionString = strConn
    
    Dim objDataSet As DataSet = New DataSet()
    Dim objAdapter As SqlDataAdapter = New SqlDataAdapter()
    Dim objCmd As SqlCommand = New SqlCommand()' Retrieve all records from employees table.
    objCmd.CommandText = "select FirstName,BirthDate from employees"
    objCmd.Connection = connection
    objAdapter.SelectCommand = objCmd
    objAdapter.Fill(objDataSet)
    
    connection.Close()' Create an instance of StringReader class that reads the XML data.
    Dim reader As StringReader = New StringReader(objDataSet.GetXml())
    Dim doc As XPathDocument = New XPathDocument(reader)' Create an XslTransform object and load xslt file.
    Dim transform As XslTransform = New XslTransform()
    transform.Load(Me.MapPath("DateTime.xslt"))'Add an object to convert DateTime format.
    Dim objDateConvertor As DateConvertor = New DateConvertor()
    Dim args As XsltArgumentList = New XsltArgumentList()
    args.AddExtensionObject("urn:ms-kb", objDateConvertor)
    
    transform.Transform(doc, args, Response.OutputStream)
    
  8. Zapisz zmiany w WebForm1.aspx.vb.

Tworzenie przykładowego dokumentu XSLT

  1. Dodaj nowy plik XSLT o nazwie DateTime.xslt do projektu internetowego DateTimeXSLT ASP.NET.

  2. Zastąp wygenerowany kod następującym kodem. (Użyj Notatnika jako narzędzia pośredniczącego, jeśli podczas próby wklejania poniższego kodu wystąpią problemy z kodowaniem lub znakiem).

    <?xml version='1.0'?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:myObj="urn:ms-kb">
        <xsl:template match="NewDataSet">
            <table>
                <xsl:attribute name="border">1</xsl:attribute>
                  <TR>
                      <TD>Employee name</TD>
                      <TD>Original DateTime Format</TD>
                      <TD>Changed DateTime Format</TD>
                  </TR>
                <xsl:apply-templates select="*"/>
            </table>
        </xsl:template>
        <xsl:template match="*">
            <TR>
                <xsl:apply-templates select="*"/>
            </TR>
        </xsl:template>
        <xsl:template match="FirstName">
            <TD>
                <xsl:value-of select="."/>
            </TD>
        </xsl:template>
        <xsl:template match="BirthDate">
        <xsl:variable name="Date" select="."/>
            <TD>
                <xsl:value-of select="$Date"/>
            </TD>
            <TD>
                <xsl:value-of select="myObj:GetDateTime($Date, 'F')"/>
            </TD>
        </xsl:template>
    </xsl:stylesheet>
    
  3. Zapisz zmiany w pliku DateTime.xslt.

Testowanie przekształcenia XSLT przy użyciu formularza internetowego ASP.NET

  1. Zapisz zmiany w projekcie internetowym DateTimeXSLT ASP.NET.
  2. W menu Kompilacja kliknij pozycję Kompiluj rozwiązanie.
  3. Uruchom program Internet Explorer i otwórz WebForm1.aspx, określając http://IISServerName/DateTimeXSLT/WebForm1.aspx adres URL, pod którym IISServerName jest nazwą serwera usług IIS.

Teraz można zobaczyć dwa formaty, DateTime format zestawu danych i przekształcony DateTime format na stronie WebForm1.aspx.DateTime