Megosztás:


XML-ből

Egy XML-sztringet tartalmazó oszlopot elemez a megadott sémával rendelkező sorba. A visszaadott nullértéket egy nem elemezhető sztring esetén adja vissza.

Szemantika

from pyspark.sql import functions as sf

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

Paraméterek

Paraméter Típus Description
col pyspark.sql.Column vagy str Egy xml formátumú oszlop vagy oszlop neve.
schema StructType, pyspark.sql.Column vagy str StructType, Column vagy Python sztringkonstans DDL formátumú sztringgel az Xml-oszlop elemzésekor.
options diktálás, nem kötelező Elemzés vezérlésének beállításai. Ugyanazokat a beállításokat fogadja el, mint az Xml-adatforrás.

Visszatérítések

pyspark.sql.Column: egy összetett típusú új oszlop adott XML-objektumból.

Példák

1. példa: XML elemzése DDL formátumú sztringsémával

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))]

2. példa: XML elemzése sémával 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}|
+---------------+

3. példa: XML elemzése ArrayType sémában

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]))]

4. példa: XML elemzése 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]))]