使用 Scala,转换的最佳方法是什么
<myapp>
<username>bill</username>
<password>secret123</password>
<background>#FFFFFF</background>
</myapp>
进入以下系统属性:
myapp.username=bill
myapp.password=secret123
myapp.background=#FFFFFF
假设转换器附加到 sys.props?
java.util.Properties支持一种 XML 格式,认为不是您描述的那种。
scala> val s = "<myapp><username>bill</username><password>secret123</password><background>#FFFFFF</background></myapp>"
s: java.lang.String = <myapp><username>bill</username><password>secret123</password><background>#FFFFFF</background></myapp>
scala> val e = xml.XML.loadString(s)
e: scala.xml.Elem = <myapp><username>bill</username><password>secret123</password><background>#FFFFFF</background></myapp>
scala> val sp = new sys.SystemProperties
sp: scala.sys.SystemProperties =
Map(env.emacs -> "", java.runtime.name -> Java(TM) SE Runtime Environment, ....)
scala> sp ++= e.child.map(n => (e.label + "." + n.label, n.text))
res11: sp.type =
Map(env.emacs -> "", java.runtime.name -> Java(TM) SE Runtime Environment, ...)
完整性检查:
scala> val p = java.lang.System.getProperties
p: java.util.Properties =
{env.emacs=, java.runtime.name=Java(TM) SE Runtime Environment,...}
scala> import collection.JavaConversions._
import collection.JavaConversions._
scala> p filter { case (k, v) => k.startsWith("myapp") } \
foreach { case (k,v) => println(k + "=" + v) }
myapp.password=secret123
myapp.background=#FFFFFF
myapp.username=bill