使用 Scala 中的属性名称读取 XML
Read XML with attribute names in Scala
我有以下 XML:
<TABLES>
<TABLE attrname="Red">
<ROWDATA>
<ROW Type="solid" track="0" Unit="0"/>
</ROWDATA>
</TABLE>
<TABLE attrname="Blue">
<ROWDATA>
<ROW Type="light" track="0" Unit="0"/>
<ROW Type="solid" track="0" Unit="0"/>
<ROW Type="solid" track="0" Unit="0"/>
</ROWDATA>
</TABLE>
我正在使用 Spark 和 Scala。我想读取 ROW 标记中的每个字段并通过属性名称进行区分。目前下面的代码只是读取 ROW 标签内的所有值,但我想根据属性名称读取它们。
val df = session.read
.option("rowTag", "ROW")
.xml(filePath)
df.show(10)
df.printSchema()
提前致谢。
检查下面的代码。
val spark = SparkSession.builder().master("local").appName("xml").getOrCreate()
import com.databricks.spark.xml._
import org.apache.spark.sql.functions._
import spark.implicits._
val xmlDF = spark.read
.option("rowTag", "TABLE")
.xml(xmlPath)
.select(explode_outer($"ROWDATA.ROW").as("row"),$"_attrname".as("attrname"))
.select(
$"row._Type".as("type"),
$"row._VALUE".as("value"),
$"row._Unit".as("unit"),
$"row._track".as("track"),
$"attrname"
)
xmlDF.printSchema()
xmlDF.show(false)
架构
root
|-- type: string (nullable = true)
|-- value: string (nullable = true)
|-- unit: long (nullable = true)
|-- track: long (nullable = true)
|-- attrname: string (nullable = true)
示例数据
+-----+-----+----+-----+--------+
|type |value|unit|track|attrname|
+-----+-----+----+-----+--------+
|solid|null |0 |0 |Red |
|light|null |0 |0 |Blue |
|solid|null |0 |0 |Blue |
|solid|null |0 |0 |Blue |
+-----+-----+----+-----+--------+
我有以下 XML:
<TABLES>
<TABLE attrname="Red">
<ROWDATA>
<ROW Type="solid" track="0" Unit="0"/>
</ROWDATA>
</TABLE>
<TABLE attrname="Blue">
<ROWDATA>
<ROW Type="light" track="0" Unit="0"/>
<ROW Type="solid" track="0" Unit="0"/>
<ROW Type="solid" track="0" Unit="0"/>
</ROWDATA>
</TABLE>
我正在使用 Spark 和 Scala。我想读取 ROW 标记中的每个字段并通过属性名称进行区分。目前下面的代码只是读取 ROW 标签内的所有值,但我想根据属性名称读取它们。
val df = session.read
.option("rowTag", "ROW")
.xml(filePath)
df.show(10)
df.printSchema()
提前致谢。
检查下面的代码。
val spark = SparkSession.builder().master("local").appName("xml").getOrCreate()
import com.databricks.spark.xml._
import org.apache.spark.sql.functions._
import spark.implicits._
val xmlDF = spark.read
.option("rowTag", "TABLE")
.xml(xmlPath)
.select(explode_outer($"ROWDATA.ROW").as("row"),$"_attrname".as("attrname"))
.select(
$"row._Type".as("type"),
$"row._VALUE".as("value"),
$"row._Unit".as("unit"),
$"row._track".as("track"),
$"attrname"
)
xmlDF.printSchema()
xmlDF.show(false)
架构
root
|-- type: string (nullable = true)
|-- value: string (nullable = true)
|-- unit: long (nullable = true)
|-- track: long (nullable = true)
|-- attrname: string (nullable = true)
示例数据
+-----+-----+----+-----+--------+
|type |value|unit|track|attrname|
+-----+-----+----+-----+--------+
|solid|null |0 |0 |Red |
|light|null |0 |0 |Blue |
|solid|null |0 |0 |Blue |
|solid|null |0 |0 |Blue |
+-----+-----+----+-----+--------+