如何创建自定义模式以在 Scala 中读取 XML

How to create a custom schema to read XML in Scala

我正在尝试使用 spark 和 scala 为以下 XML 定义自定义架构。

<CONTAINER>
    <TABLE attrname="Wood">
        <ROWDATA>
            <ROW Weight="55" Length="11" Unit="5"/>
        </ROWDATA>
    </TABLE>
    <TABLE attrname="Metal">
        <ROWDATA>
            <ROW Weight="66" Length="23" Unit="0"/>
            <ROW Weight="44" Length="22" Unit="0"/>
            <ROW Weight="33" Length="21" Unit="1"/>
        </ROWDATA>
    <TABLE attrname="Plastic">
        <ROWDATA>
            <ROW Weight="33" Length="11" Unit="0"/>
        </ROWDATA>
    </TABLE>
<CONTAINER>

这是我试过的代码,但如果我打印数据框,它不会给我任何输出。我还需要数据框中的属性名称。非常感谢在正确指定模式方面的一些帮助。

    val xmlDFF = session.read
    .option("rootTag", "CONTAINER")
     .option("rowTag", "TABLE")
     .schema(getContainderSchema)
      .xml(filePath)


def getContainderSchema: StructType = {

     val row = new StructType()
       .add("_Weight", StringType)
       .add("_Length", StringType)
       .add("_Unit", StringType)

     val rowdata = new StructType()
       .add("ROWDATA", ArrayType(row))
}

您需要添加“TABLE”类型:

  val rowType = new StructType()
    .add("_Weight", StringType)
    .add("_Length", StringType)
    .add("_Unit", StringType)

  val rowDataType = new StructType()
    .add("ROW", ArrayType(rowType))

  val tableType = new StructType()
    .add("_attrname", StringType)
    .add("ROWDATA", rowDataType)

并使用它:

.schema(tableType)