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
from pyspark.sql import functions as sf
sf.from_xml(col, schema, options=None)
parameter
parameter | Type | Description |
|---|---|---|
|
| Une colonne ou un nom de colonne au format XML. |
|
| 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. |
| 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
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()
[Row(xml=Row(a=1))]
Exemple 2 : Analyse du code XML avec un schéma StructType
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()
+---------------+
|from_xml(value)|
+---------------+
| {1}|
+---------------+
Exemple 3 : Analyse XML avec ArrayType dans le schéma
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()
[Row(xml=Row(a=[1, 2]))]
Exemple 4 : Analyse de code XML à l'aide de schema_of_xml
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()
[Row(xml=Row(a=[1, 2]))]