メインコンテンツまでスキップ

from_xml

XML 文字列を含む列を、指定されたスキーマを持つ行に解析します。解析できない文字列の場合はnull返します。

構文

Python
from pyspark.sql import functions as sf

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

パラメーター

パラメーター

Type

説明

col

pyspark.sql.Column またはstr

XML 形式の列または列名。

schema

StructTypepyspark.sql.Columnまたはstr

Xml 列を解析するときに使用する DDL 形式の文字列を含む StructType、Column、または Python 文字列リテラル。

options

辞書(オプション)

解析を制御するためのオプション。Xml データ ソースと同じオプションを受け入れます。

戻り値

pyspark.sql.Column: 指定された XML オブジェクトからの複合型の新しい列。

例1 : DDL形式の文字列スキーマを使用したXMLの解析

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

例2 : StructTypeスキーマを使用したXMLの解析

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}|
+---------------+

例3 : スキーマ内のArrayTypeを含むXMLの解析

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

例4 : XMLの解析 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]))]