Partager via


from_xml

Analyse une colonne contenant une chaîne XML sur une ligne avec le schéma spécifié. Retourne null, dans le cas d’une chaîne nonparsable.

Syntaxe

from pyspark.sql import functions as sf

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

Paramètres

Paramètre Type Descriptif
col pyspark.sql.Column ou str Un nom de colonne ou de colonne au format XML.
schema StructTypeou pyspark.sql.Column str Littéral de chaîne StructType, Column ou Python avec une chaîne au format DDL à utiliser lors de l’analyse de la colonne Xml.
options dict, facultatif Options pour contrôler l’analyse. Accepte les mêmes options que la source de données Xml.

Retours

pyspark.sql.Column: nouvelle colonne de type complexe à partir d’un objet XML donné.

Examples

Exemple 1 : Analyse du code XML avec un schéma de chaîne au format 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 StructType schéma

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 du code XML avec ArrayType 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 du 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]))]