Condividi tramite


Esempio: Specifica la direttiva ELEMENT e la codifica di entità

Si applica a:SQL ServerDatabase SQL di AzureIstanza gestita di SQL di Azure

In questo esempio viene illustrata la differenza fra le direttive ELEMENT e XML . La direttiva ELEMENT converte i dati in entità, ma la direttiva XML non lo fa. Nella query, all'elemento <Summary> viene assegnato codice XML, <Summary>This is summary description</Summary>.

Considerare la query seguente:

USE AdventureWorks2022;
GO
SELECT  1 as Tag,
        0 as Parent,
        ProductModelID  as [ProductModel!1!ProdModelID],
        Name            as [ProductModel!1!Name],
        NULL            as [Summary!2!SummaryDescription!ELEMENT]
FROM    Production.ProductModel
WHERE   ProductModelID=19
UNION ALL
SELECT  2 as Tag,
        1 as Parent,
        ProductModelID,
        NULL,
       '<Summary>This is summary description</Summary>'
FROM   Production.ProductModel
WHERE  ProductModelID = 19
FOR XML EXPLICIT;

Di seguito è riportato il risultato. Nel risultato, la descrizione di riepilogo è trasformata in entità.

<ProductModel ProdModelID="19" Name="Mountain-100">
  <Summary>
    <SummaryDescription><Summary>This is summary description</Summary></SummaryDescription>
  </Summary>
</ProductModel>

Se nel nome della colonna si specifica la direttiva XML, Summary!2!SummaryDescription!XML, invece della direttiva ELEMENT, si otterrà la descrizione di riepilogo senza entitizzazione.

<ProductModel ProdModelID="19" Name="Mountain-100">
  <Summary>
    <SummaryDescription>
      <Summary>This is summary description</Summary>
    </SummaryDescription>
  </Summary>
</ProductModel>

Invece di assegnare un valore XML statico, la query seguente usa il metodo query() del tipo xml per recuperare la descrizione di riepilogo del modello di prodotto dalla colonna CatalogDescription di tipo xml. Poiché si sa che il risultato è di tipo xml, non viene applicato alcun processo di entitizzazione.

SELECT  1 as Tag,
        0 as Parent,
        ProductModelID  as [ProductModel!1!ProdModelID],
        Name            as [ProductModel!1!Name],
        NULL            as [Summary!2!SummaryDescription]
FROM    Production.ProductModel
WHERE   CatalogDescription is not null
UNION ALL
SELECT  2 as Tag,
        1 as Parent,
        ProductModelID,
        Name,
       (SELECT CatalogDescription.query('
            declare namespace pd="http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelDescription";
			/pd:ProductDescription/pd:Summary'))
FROM     Production.ProductModel
WHERE    CatalogDescription is not null
ORDER BY [ProductModel!1!ProdModelID],Tag
FOR XML EXPLICIT;

Vedi anche