Compartir a través de


Cómo: Leer datos con establecimiento de tipos con una asignación de esquema

En el siguiente ejemplo se utiliza XmlReader para devolver un objeto con establecimiento de tipos. A causa del formato del elemento hire-date, no se puede convertir correctamente en un objeto DateTime. Sin embargo, si utiliza un esquema para asignar el elemento al tipo xs:date, puede realizar la conversión de tipo necesaria.

Ejemplo

En el siguiente ejemplo se utiliza el método ReadElementContentAsDateTime para devolver el elemento hire-date como un objeto DateTime.

' Create a validating XmlReader object. The schema 
' provides the necessary type information.
Dim settings As XmlReaderSettings = New XmlReaderSettings()
settings.ValidationType = ValidationType.Schema
settings.Schemas.Add("urn:empl-hire", "hireDate.xsd")
Using reader As XmlReader = XmlReader.Create("hireDate.xml", settings) 
  ' Move to the hire-date element.
  reader.MoveToContent()
  reader.ReadToDescendant("hire-date")

  ' Return the hire-date as a DateTime object.
  Dim hireDate As DateTime = reader.ReadElementContentAsDateTime()
  Console.WriteLine("Six Month Review Date: {0}", hireDate.AddMonths(6))
End Using
// Create a validating XmlReader object. The schema 
// provides the necessary type information.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add("urn:empl-hire", "hireDate.xsd");
using (XmlReader reader = XmlReader.Create("hireDate.xml", settings)) {

  // Move to the hire-date element.
  reader.MoveToContent();
  reader.ReadToDescendant("hire-date");

  // Return the hire-date as a DateTime object.
  DateTime hireDate = reader.ReadElementContentAsDateTime();
  Console.WriteLine("Six Month Review Date: {0}", hireDate.AddMonths(6));
}

Entrada

En el ejemplo se utilizan los archivos hireDate1.xml y hireDate.xsd como entrada.

hireDate.xml

<employee xmlns="urn:empl-hire">
    <ID>12365</ID>
    <hire-date>2003-01-08</hire-date>
    <title>Accountant</title>
</employee>

hireDate.xsd

<?xml version="1.0"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="urn:empl-hire" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="employee">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="ID" type="xs:unsignedShort" />
        <xs:element name="hire-date" type="xs:date" />
        <xs:element name="title" type="xs:string" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Salida

Six Month Review Date:  7/8/2003 12:00:00 AM

Vea también

Conceptos

Leer fragmentos de XML con XmlReader

Lectura de datos de tipo