scala解析xml工具

解析xml至Map

标签名称用下划线连接

  /**
   * 读取xml 至map
   */
  def readXml2Map(filePath: String): scala.collection.mutable.Map[String, String] = {
    val xmlFile = XML.loadFile(filePath) // 根节点
    val childNodes = xmlFile.child // 所有一级节点
    val xmlContentMap: scala.collection.mutable.Map[String, String] = scala.collection.mutable.Map()
    for (childNode <- childNodes) {
      readXml(childNode, childNode.label, xmlContentMap)
    }
    return xmlContentMap
  }

  def readXml(parentNode: Node, parentLabel: String, xmlContentMap: scala.collection.mutable.Map[String, String]): Unit = {
    if (!"#PCDATA".equals(parentLabel)) {
      if (!hasChildNodes(parentNode)) {
        println(String.format("%-30s%s", parentLabel, parentNode.text))
        xmlContentMap += (parentLabel -> parentNode.text)
      } else {
        for (node <- parentNode.\("_")) {
          readXml(node, parentLabel + "_" + node.label, xmlContentMap)
        }
      }
    }
  }
 /**
   * 判断当前节点是否有子节点
   * @param node
   * @return true: 有子节点
   */
  def hasChildNodes(node: Node): Boolean = {
    return node.\("_").length != 0
  }

你可能感兴趣的:(scala)