【问题标题】:Read the input xml data from HDFS using scala使用 scala 从 HDFS 读取输入 xml 数据
【发布时间】:2017-03-16 07:37:50
【问题描述】:

我正在尝试使用 Scala 中的 Xml 加载来解析 Xml 文件。 但是这个程序不能从 HDFS 读取输入数据。 它只能从本地文件系统中读取。

有人可以帮助我如何从 HDFS 读取输入数据。

尝试了以下程序:

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import scala.collection.mutable.WrappedArray
import scala.collection.immutable.HashMap
import scala.collection.immutable.HashMap
import scala.collection.immutable.HashMap

object ProcessxmlInputFiles {

  def main(args: Array[String]) {
    val sc = new SparkContext(new SparkConf().setAppName("Parse XML Data").setMaster("local[*]"))
    val rawRDD = xml.XML.load(args(0))
    rawRDD.child.foreach { x =>
        var dateTime = StringBuilder.newBuilder
        x.child.foreach { x =>
          if ("header".equals(x.label)) {
            dateTime.append(x.child(1).attribute("dateTime").get.toString())
          }
          ...
         }
         ...
       }
         ...
       sc.stop
      }
 }

提前致谢!!

【问题讨论】:

  • 您作为 args 的输入是什么?

标签: xml scala apache-spark spark-dataframe


【解决方案1】:

您可以为xml 使用databricks 库

//imports
import org.apache.spark.sql.SQLContext
import org.apache.spark.sql.types.{StructType, StructField, StringType, DoubleType};

/define schema for xml
val sqlContext = new SQLContext(sc)
val customSchema = StructType(Array(
    StructField("_id", StringType, nullable = true),
    StructField("column1", StringType, nullable = true),
    StructField("column2", StringType, nullable = true)))

//read xml file
val df = sqlContext.read
    .format("com.databricks.spark.xml")
    .option("rowTag", "item")
    .schema(customSchema)
    .load("file.xml") //You can provide local file "file:///<path to your xml>" for hdfs "hdfs://<path to file>"

//write the result
val selectedData = df.select("column1", "_id")
selectedData.write
    .format("com.databricks.spark.xml")
    .option("rootTag", "items")
    .option("rowTag", "item")
    .save("newfile.xml")

【讨论】:

  • 您好 Faig,感谢您的回复。这里我不想使用 Dataframe。
  • 我只想使用 XML 加载器处理它。我已经准备好逻辑,但唯一担心的是它没有从 HDFS 获取数据。有没有办法使用 xml 加载器从 HDFS 读取数据跨度>
  • 根据文件大小,方法可能会有所不同。
猜你喜欢
  • 2017-05-26
  • 1970-01-01
  • 1970-01-01
  • 2018-10-21
  • 2021-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-20
相关资源
最近更新 更多