Aller au contenu principal

from_xml

Analyse une colonne contenant une chaîne XML en une ligne avec le schéma spécifié. Renvoie null, dans le cas d'une chaîne non analysable.

Syntaxe

Python
from pyspark.sql import functions as sf

sf.from_xml(col, schema, options=None)

parameter

parameter

Type

Description

col

pyspark.sql.Column ou str

Une colonne ou un nom de colonne au format XML.

schema

StructType, pyspark.sql.Column ou str

Une chaîne de caractères littérale StructType, Column ou Python avec une chaîne formatée DDL à utiliser lors de l'analyse de la colonne Xml.

options

dictionnaire, facultatif

Options pour contrôler l'analyse. Accepte les mêmes options que la source de données Xml.

parameter

Type

Description

col

pyspark.sql.Column ou str

Une colonne ou un nom de colonne au format XML.

schema

StructType, pyspark.sql.Column ou str

Une chaîne de caractères littérale StructType, Column ou Python avec une chaîne formatée DDL à utiliser lors de l'analyse de la colonne Xml.

options

dictionnaire, facultatif

Options pour contrôler l'analyse. Accepte les mêmes options que la source de données Xml.

Renvoie

pyspark.sql.ColumnUne nouvelle colonne de type complexe à partir de l'objet XML donné.

Exemples

Exemple 1 : analyse de XML avec un schéma de chaîne formaté en DDL

Python
import pyspark.sql.functions as sf
data = [(1, '''<p><a>1</a></p>''')]
df = spark.createDataFrame(data, ("key", "value"))
# Define the schema using a DDL-formatted string
schema = "STRUCT<a: BIGINT>"
# Parse the XML column using the DDL-formatted schema
df.select(sf.from_xml(df.value, schema).alias("xml")).collect()
Output
[Row(xml=Row(a=1))]

Exemple 2 : Analyse du code XML avec un schéma StructType

Python
import pyspark.sql.functions as sf
from pyspark.sql.types import StructType, LongType
data = [(1, '''<p><a>1</a></p>''')]
df = spark.createDataFrame(data, ("key", "value"))
schema = StructType().add("a", LongType())
df.select(sf.from_xml(df.value, schema)).show()
Output
+---------------+
|from_xml(value)|
+---------------+
| {1}|
+---------------+

Exemple 3 : Analyse XML avec ArrayType dans le schéma

Python
import pyspark.sql.functions as sf
data = [(1, '<p><a>1</a><a>2</a></p>')]
df = spark.createDataFrame(data, ("key", "value"))
# Define the schema with an Array type
schema = "STRUCT<a: ARRAY<BIGINT>>"
# Parse the XML column using the schema with an Array
df.select(sf.from_xml(df.value, schema).alias("xml")).collect()
Output
[Row(xml=Row(a=[1, 2]))]

Exemple 4 : Analyse de code XML à l'aide de schema_of_xml

Python
import pyspark.sql.functions as sf
# Sample data with an XML column
data = [(1, '<p><a>1</a><a>2</a></p>')]
df = spark.createDataFrame(data, ("key", "value"))
# Generate the schema from an example XML value
schema = sf.schema_of_xml(sf.lit(data[0][1]))
# Parse the XML column using the generated schema
df.select(sf.from_xml(df.value, schema).alias("xml")).collect()
Output
[Row(xml=Row(a=[1, 2]))]