解析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
}