共用方式為


從 XML 匯入

解析包含 XML 字串的欄位,將其解析為具有指定模式的列。 對於不可解析字串,則返回 null

語法

from pyspark.sql import functions as sf

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

參數

參數 類型 Description
col pyspark.sql.Column 或 str 一個以 XML 格式呈現的欄位名稱。
schema StructTypepyspark.sql.Column 或稱力量 一個 StructType、Column 或 Python 字串的字面值,搭配 DDL 格式的字串,用於解析 Xml 欄位。
options DICT,選擇性 控制解析的選項。 接受與 XML 資料來源相同的選項。

退貨

pyspark.sql.Column: 來自給定 XML 物件的複數型新欄位。

範例

範例 1:使用 DDL 格式字串結構解析 XML

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:用 StructType 結構解析 XML

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:解析 XML 與 ArrayType in schema

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:使用 XML 解析 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]))]