本文整理汇总了Scala中scala.xml.XML类的典型用法代码示例。如果您正苦于以下问题:Scala XML类的具体用法?Scala XML怎么用?Scala XML使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了XML类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: checkVersion
//设置package包名称以及导入依赖的类
package uk.co.telegraph.sbt.resolver
import java.net.URL
import sbt.CrossVersion._
import sbt._
import scala.xml.XML
trait ModuleResolver {
implicit val repository :Repository
implicit val scalaVersion:String
val module:ModuleID
lazy val groupId = module.organization
lazy val artifactId = module.crossVersion match {
case Disabled => module.name
case _ => s"${module.name}_$scalaVersion"
}
lazy val revision = module.revision
private [resolver] lazy val metadata = loadMetadata
//Check if version exists
def checkVersion(version:String) =
metadata.versions.contains(version)
def resolveVersion(versionOpt:Option[String] = None):ModuleResolver = {
val resolvedVersion:Option[String] = versionOpt.orElse( Some(revision) )
val versionLabel = resolvedVersion
.map({
case LatestVersionLabel => metadata.latest
case ReleaseVersionLabel => metadata.release
case version => version
})
.filter(checkVersion)
.getOrElse(metadata.latest)
fromModuleIdAndMetadata(module.copy(revision = versionLabel), metadata)
}
//Get remove Jar
def remoteJar:URL = artifactUrl
private [resolver] def metadataUrl:URL =
url(s"${repository.url}/${groupId.replaceAll("\\.", "/")}/$artifactId/${repository.metadata}")
private [resolver] def artifactUrl:URL =
url(s"${repository.url}/${groupId.replaceAll("\\.", "/")}/$artifactId/$revision/$artifactId-$revision.jar")
private [resolver] def loadMetadata:ModuleMetadata = {
val versioning = XML.load( metadataUrl ) \\ "versioning"
val versions = (versioning \ "versions" \ "version").map(_.text)
val release = (versioning \ "release").text
val latest = (versioning \ "latest").text
ModuleMetadata(versions, release, latest)
}
}
示例2: OSMParser
//设置package包名称以及导入依赖的类
package tosidewalk
import scala.collection.mutable
import scala.xml.XML
class OSMParser {
def parse = {
val xml = XML.loadFile("data/shadyside.osm")
// Parse all the streets from the xml file
val streets = for {
way <- xml \ "way"
tags = way \\ "tag"
streetness <- tags.map(t => (t \ "@k").toString -> (t \ "@v").toString).filter {
case (k, v) =>
(k == "highway") &&
(v == "trunk" || v == "primary" || v == "secondary" || v == "tertiary" || v == "residential")
}
} yield way
// Find the intersections where *three* or more streets share a node
val nodeToWays = new mutable.HashMap[String, mutable.ListBuffer[String]]()
for {
street <- streets
node <- street \\ "nd"
} {
val wayId = (street \ "@id").toString
val nodeId = (node \ "@ref").toString
if (nodeToWays.contains(wayId)) {
nodeToWays(wayId) += nodeId
} else {
nodeToWays(wayId) = mutable.ListBuffer(nodeId)
}
}
val intersectionNodeIds = nodeToWays.filter(_._2.length > 2).keys
// Split the streets at intersections
for {
street <- streets
} {
val nodes = (street \\ "nd").map(_ \ "@ref").map(_.toString)
println(nodes)
}
}
}
示例3: LogBack
//设置package包名称以及导入依赖的类
package gitbucket.monitoring.services
import java.nio.file.{Files, Paths}
import scala.xml.XML
import gitbucket.core.util.StringUtil
import gitbucket.monitoring.models.{LogBackInfo}
import gitbucket.monitoring.utils._
object LogBack {
val notFoundMessage = "Can not find logback configuration file."
val dosentConfigureMessage = "Dosen't configure Logback."
val enableLogging = Java.getSystemProperties.contains("logback.configurationFile")
val confPath = Java.getSystemProperties.getOrElse("logback.configurationFile", notFoundMessage)
val logBackSettingsFile: Either[String, String] = {
if (enableLogging) {
try {
val bytes = Files.readAllBytes(Paths.get(confPath))
(Right(
StringUtil.convertFromByteArray(bytes)
))
} catch {
case e: Exception => Left(Message.error)
}
} else {
Left(dosentConfigureMessage)
}
}
val logFilePath: Either[String, String] = {
if (enableLogging) {
try {
val xml = logBackSettingsFile match {
case Left(message) => message
case Right(s) => {
(XML.loadString(s) \\ "appender" \ "file" toString).replace("<file>","").replace("</file>","")
}
}
if (xml.trim.length == 0) {
Left(Message.notFound)
} else {
Right(xml)
}
} catch {
case e: Exception => Left(Message.error)
}
} else {
Left(dosentConfigureMessage)
}
}
def getLogBackSettings: LogBackInfo = {
LogBackInfo(
Java.getSystemProperties.contains("logback.configurationFile"),
Java.getSystemProperties.getOrElse("logback.configurationFile", notFoundMessage),
logFilePath
)
}
}
示例4: OpenHubMetadataFetcher
//设置package包名称以及导入依赖的类
package cloud.hw.util
import com.typesafe.scalalogging._
import org.slf4j.LoggerFactory
import scala.xml.{XML}
object OpenHubMetadataFetcher {
def forUrl(url: String) = new OpenHubMetadataFetcher(url).download()
def forKeyId(apiKey: String, id: Int) = {
forUrl(s"https://www.openhub.net/p/${id}.xml?api_key=${apiKey}&v=1")
}
}
class OpenHubMetadataFetcher(url: String) {
private val logger = Logger(LoggerFactory.getLogger(this.getClass))
def download(): Map[String, String] = {
logger.info(s"downloading from $url")
val id = 0
val xml = XML.load(new java.net.URL(url))
val downUrl = (xml \ "result" \ "project" \ "download_url").text
logger.trace(xml toString)
Map(
"downloadUrl" -> downUrl,
"projectName" -> (xml \ "result" \ "project" \ "name").text,
"tags" -> (xml \ "result" \ "project" \ "tags" \ "tag").map(n => n.text).mkString(",")
)
}
}
示例5: Img2TxtProcessor
//设置package包名称以及导入依赖的类
package pl.mojepanstwo.sap.toakoma.processors
import java.io.{File, FileInputStream, InputStreamReader}
import org.springframework.batch.item.ItemProcessor
import pl.mojepanstwo.sap.toakoma._
import scala.xml.{Elem, Node, XML}
import scala.xml.transform.RewriteRule
import sys.process._
class Img2TxtProcessor extends ItemProcessor[Model, Model] {
override def process(item:Model): Model = {
item.linksHtml.foreach { case (key, dirPath) =>
try {
val xml = XML.load(new InputStreamReader(new FileInputStream(item.xmlPath(key)), "UTF-8"))
val changed = new RewriteRule {
override def transform(n: Node): Seq[Node] = n match {
case elem @ Elem(_, "img", _, _, child @ _*) => {
val src = elem.attribute("src").get
val imageFile = new File(dirPath + "/" + src)
val cmd = "tesseract " +
imageFile.getAbsolutePath + " " +
"stdout " +
"-l pol"
var result = cmd !!
if(Option(result).exists(_.trim.isEmpty)) return n
result = result.replaceAll("-\n", "")
result = result.replaceAll("—\n", "")
return(<textFromImg>{result}</textFromImg>)
}
case elem: Elem => elem copy (child = elem.child flatMap (this transform))
case other => other
}
} transform xml
XML.save(dirPath + "/text_from_image.xml", changed(0), "UTF-8", true)
item.xmlPath(key) = dirPath + "/text_from_image.xml"
} catch {
case e: Throwable => println(e.printStackTrace())
}
}
item
}
}
示例6: convertDict
//设置package包名称以及导入依赖的类
import scala.xml.XML
import fileIO._
import toyaml._
object convertDict {
def main(args: Array[String]): Unit = {
var infile:String = ""
var outfile:String = "filters.yaml"
var itype:String = "filter"
val xml = XML.loadFile(infile)
val file = new OutputFiles(outfile)
itype match {
case "idiom" => new toyaml.ToIdiomYaml(xml, file).convert
case "cchart" => new toyaml.ToCchartYaml(xml, file).convert
case "category" => new toyaml.ToCategoryYaml(xml, file).convert
case "frame" => new toyaml.ToFrameYaml(xml, file).convert
case "filter" => new toyaml.ToFilterYaml(xml, file).convert
case _ => println("not type")
}
file.close
println("done")
}
}
示例7: ConnectionProperties
//设置package包名称以及导入依赖的类
package info.armado.ausleihe.client.model
import better.files.File
import scala.xml.XML
import scala.xml.PrettyPrinter
object ConnectionProperties {
def apply(propertiesFile: File): ConnectionProperties = {
val contentNode = XML.loadFile(propertiesFile.toJava)
val url = (contentNode \ "url").text
val port = (contentNode \ "port").text.toInt
val basePath = (contentNode \ "basepath").text
val operator = Operators.parse((contentNode \ "operator").text)
ConnectionProperties(url, port, basePath, operator)
}
def createDefault = ConnectionProperties("localhost", 8080, "ausleihe-rest-server", Some(Operators.Spielekreis))
}
case class ConnectionProperties(val url: String, val port: Int, val basePath: String, operator: Option[Operators.Value]) {
val baseURL = s"http://${url}:${port}/${basePath}"
def saveToFile(propertiesFile: File) = {
val content =
<connection>
<url>{ url }</url>
<port>{ port }</port>
<basepath>{ basePath }</basepath>
<operator>{
operator match {
case Some(operator) => operator.toString.toLowerCase
case None => "unknown"
}
}</operator>
</connection>
val prettyPrinter = new PrettyPrinter(80, 2)
propertiesFile.overwrite(prettyPrinter.format(content))
}
}
示例8: GpxFileReader
//设置package包名称以及导入依赖的类
package eu.kraml.io
import java.io.File
import java.nio.file.Path
import java.time.Instant
import java.time.format.DateTimeFormatter
import eu.kraml.model.{GpsCoordinate, Record}
import scala.collection.mutable.ListBuffer
import scala.xml.XML
object GpxFileReader {
val formatter = DateTimeFormatter.ISO_INSTANT
def read(gpxFile: Path): Option[List[Record]] = {
read(gpxFile.toFile)
}
def read(gpxFile: File): Option[List[Record]] = {
try {
Some(readInternal(gpxFile))
} catch {
case e:Exception =>
None
}
}
private def readInternal(gpxFile: File): List[Record] = {
val gpx = XML.loadFile(gpxFile)
val segment = gpx \ "trk" \ "trkseg"
val points = segment \ "trkpt"
val records = ListBuffer[Record]()
points.foreach(n => {
val lat = n.attribute("lat").get.head.text
val lon = n.attribute("lon").get.head.text
val timestampText = (n \ "time").text
val timestamp = Instant.parse(timestampText)
records += Record(new GpsCoordinate(lat.toDouble, lon.toDouble), timestamp)
})
records.toList
}
}
示例9: EndpointsSpec
//设置package包名称以及导入依赖的类
package moe.pizza.eveapi
import org.scalatest.{Matchers, FlatSpec}
import moe.pizza.eveapi.generated.{char, account}
import scala.io.Source
import scala.xml.XML
class EndpointsSpec extends FlatSpec with Matchers {
class EndpointTester[T](data: String)(implicit val parser: scalaxb.XMLFormat[T]) {
def apply() = {
s"$data" should "parse correctly with the generated classes" in {
val xml = Source.fromURL(getClass.getResource(data)).getLines().mkString("\n")
scalaxb.fromXML[T](XML.loadString(xml))
}
}
}
// Account
new EndpointTester[account.AccountStatus.Eveapi]("/raw/account/AccountStatus.xml").apply()
new EndpointTester[account.APIKeyInfo.Eveapi]("/raw/account/APIKeyInfo.xml").apply()
new EndpointTester[account.Characters.Eveapi]("/raw/account/Characters.xml").apply()
// Characters
new EndpointTester[char.AccountBalance.Eveapi]("/raw/char/AccountBalance.xml").apply()
new EndpointTester[char.AssetList.Eveapi]("/raw/char/AssetList.xml").apply()
new EndpointTester[char.Blueprints.Eveapi]("/raw/char/Blueprints.xml").apply()
new EndpointTester[char.CharacterInfo.Eveapi]("/raw/char/CharacterInfo.xml").apply()
new EndpointTester[char.ContactList.Eveapi]("/raw/char/ContactList.xml").apply()
new EndpointTester[char.ContractItems.Eveapi]("/raw/char/ContractItems.xml").apply()
new EndpointTester[char.Contracts.Eveapi]("/raw/char/Contracts.xml").apply()
// new EndpointTester[char.KillMails.Eveapi]("/raw/char/KillMails.xml").apply() pending a better XML parser for KMs
new EndpointTester[char.MailBodies.Eveapi]("/raw/char/MailBodies.xml").apply()
new EndpointTester[char.MailMessages.Eveapi]("/raw/char/MailMessages.xml").apply()
new EndpointTester[char.MarketOrder.Eveapi]("/raw/char/MarketOrder.xml").apply()
new EndpointTester[char.Medals.Eveapi]("/raw/char/Medals.xml").apply()
new EndpointTester[char.Notifications.Eveapi]("/raw/char/Notifications.xml").apply()
new EndpointTester[char.NotificationTexts.Eveapi]("/raw/char/NotificationTexts.xml").apply()
new EndpointTester[char.SkillInTraining.Eveapi]("/raw/char/SkillInTraining.xml").apply()
new EndpointTester[char.SkillQueue.Eveapi]("/raw/char/SkillQueue.xml").apply()
new EndpointTester[char.Standings.Eveapi]("/raw/char/Standings.xml").apply()
new EndpointTester[char.UpcomingCalendarEvents.Eveapi]("/raw/char/UpcomingCalendarEvents.xml").apply()
new EndpointTester[char.WalletJournal.Eveapi]("/raw/char/WalletJournal.xml").apply()
new EndpointTester[char.WalletTransactions.Eveapi]("/raw/char/WalletTransactions.xml").apply()
}
示例10: S3Api
//设置package包名称以及导入依赖的类
package io.github.daviddenton.finagle.aws
import com.twitter.finagle.Service
import com.twitter.finagle.http.Method.{Delete, Get, Put}
import com.twitter.finagle.http.Status.{NoContent, NotFound, Ok}
import com.twitter.finagle.http.{Request, Response}
import com.twitter.util.Future
import scala.xml.XML
object S3Api {
def apply(client: Service[Request, Response]): S3Api = new S3Api {
override def list(): Future[Seq[Bucket]] = client(Request(Get, "/")).map(_.contentString).map(XML.loadString).map(S3.buckets)
override def +=(bucket: Bucket): Future[Bucket] = {
val request = Request(Put, "/" + bucket.name)
client(request).flatMap {
rsp =>
rsp.status match {
case Ok => Future(bucket)
case _ => Future.exception(new IllegalArgumentException("AWS returned " + rsp.status))
}
}
}
override def -=(bucket: Bucket): Future[Option[Bucket]] =
client(Request(Delete, "/" + bucket.name)).flatMap {
rsp =>
rsp.status match {
case NoContent => Future(Option(bucket))
case NotFound => Future(None)
case _ => Future.exception(new IllegalArgumentException("AWS returned " + rsp.status))
}
}
}
}
trait S3Api {
def list(): Future[Seq[Bucket]]
def +=(bucket: Bucket): Future[Bucket]
def -=(bucket: Bucket): Future[Option[Bucket]]
}
示例11: SimpleTransformationStd
//设置package包名称以及导入依赖的类
package net.michalsitko.xml.bench
import java.io.StringWriter
import scala.xml.{Elem, Node, Text, XML}
object SimpleTransformationStd extends SimpleTransformation {
val doTransform: PartialFunction[Node, Node] = {
case el: Elem if el.label == "f" =>
if(el.child.size == 1) {
val replaceWith = el.child.head match {
case t: Text =>
Text(t.text.toUpperCase)
case a => a
}
el.copy(child = List(replaceWith))
} else {
el
}
case a => a
}
override def transform(input: String): String = {
val xml = XML.loadString(input)
val transformed = xml.map {
case el: Elem if el.label == "a" =>
el.copy(child = el.child.flatMap { el =>
doTransform(el)
})
case a => a
}
val writer = new StringWriter
XML.write(writer, transformed.head, "UTF-8", true, null)
writer.toString
}
}
示例12: PrintBenchParams
//设置package包名称以及导入依赖的类
package net.michalsitko.xml.bench
import java.io.StringWriter
import java.util.concurrent.TimeUnit
import net.michalsitko.xml.entities.LabeledElement
import net.michalsitko.xml.parsing.XmlParser
import net.michalsitko.xml.printing.XmlPrinter
import org.openjdk.jmh.annotations._
import scala.xml.{Elem, XML}
object PrintBenchParams {
val lensElement: LabeledElement =
XmlParser.parse(Roundtrip.example.input).right.get
val stdElement: Elem =
XML.loadString(Roundtrip.example.input)
}
@BenchmarkMode(Array(Mode.AverageTime))
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Benchmark)
class PrintBench {
import PrintBenchParams._
@Benchmark def printWithLens: String = {
XmlPrinter.print(lensElement)
}
@Benchmark def prettyPrintWithLens: String = {
XmlPrinter.print(lensElement)
}
@Benchmark def prettyPrintWithStd: String = {
val writer = new StringWriter
XML.write(writer, stdElement, "UTF-8", true, null)
writer.toString
}
}
示例13: ZipImplicits
//设置package包名称以及导入依赖的类
package anchorman.docx
import anchorman.media.MediaFile
import java.io.OutputStreamWriter
import java.util.zip.{ZipEntry, ZipOutputStream}
import scala.xml.{MinimizeMode, NodeSeq, XML}
object ZipImplicits {
implicit class ZipOutputStreamOps(out: ZipOutputStream) {
def writeXmlFile(path: String, nodes: NodeSeq): Unit = {
out.putNextEntry(new ZipEntry(path))
val writer = new OutputStreamWriter(out)
try XML.write(writer, nodes.head, "UTF-8", true, null, MinimizeMode.Always)
finally writer.flush()
}
def writeMediaFile(path: String, file: MediaFile): Unit = {
out.putNextEntry(new ZipEntry(path))
try out.write(file.content)
finally out.flush()
}
}
}
示例14: Util
//设置package包名称以及导入依赖的类
package trap.xml
//import java.io.BufferedInputStream
//import java.io.BufferedOutputStream
//import java.io.BufferedReader
//import java.io.File
import java.io.FileInputStream
import java.io.InputStreamReader
import scala.xml.Elem
import scala.xml.Attribute
import scala.xml.Text
import scala.xml.Node
import scala.xml.NodeSeq
import scala.xml.Null
import scala.xml.PrettyPrinter
import scala.xml.XML
import trap.Util._
import trap.file.Util._
object Util {
def formatNicely(xmlFile:String) =
writeToTextFile(xmlFile, new PrettyPrinter(200, 2).format(loadXML(xmlFile)))
def formatNicely(xml:Elem) = new PrettyPrinter(200, 2).format(xml)
def getAttributeText(xml:NodeSeq, attrName:String) = {
printdbg (" ===> getAttributeTest "+xml+": "+attrName)
(xml \ ("@"+attrName)).text
}
private val r = <root/>
def getNode(n:String) = r.copy(label=n)
def addChild(n: Node, newChild: Node) = n match {
case Elem(prefix, label, attribs, scope, child @ _*) =>
Elem(prefix, label, attribs, scope, child ++ newChild : _*)
case _ => throw new Exception("Can only add children to elements!")
}
def addChildren(n:Node, children:NodeSeq) = children.foldLeft(n)((x, y) => addChild(x, y))
def addAttribute(n:Elem, attrName:String, attrValue:String) = n % Attribute(None, attrName, Text(attrValue), Null)
def attr(xml:Node, attrName:String) = (xml \ ("@"+attrName)).text
def loadXML(fileName:String) =
using(new FileInputStream(fileName)){
fis => using(new InputStreamReader(fis)){
isr => XML.load(isr)
}
}
def getElementName (x:Node) = x.nameToString(new StringBuilder).toString
def filterByAttr(xml:NodeSeq, attrName:String, attrValue:String) =
xml.filter(x => (x \ ("@"+attrName)).text == attrValue)
def getElementsWithAttribute(xml:NodeSeq, elementName:String, attrName:String, attrVal:String) =
xml \ elementName collect { x => (x \ ("@"+attrName)).map(_.text).contains(attrVal) match {
case true => x
}
}
def getElementWithAttribute(xml:NodeSeq, elementName:String, attrName:String, attrVal:String) =
((xml \ elementName).find{ x => (x \ ("@"+attrName)).map(_.text).contains(attrVal) }).get
def getChildren(xml:NodeSeq) = xml \ "_"
}
示例15: SitemapFileSpec
//设置package包名称以及导入依赖的类
package la.dp.sitemap
import java.io.File
import java.net.URL
import org.scalatest.BeforeAndAfter
import scala.xml.{Elem, XML}
class SitemapFileSpec extends SitemapSpec with BeforeAndAfter with SitemapFile {
val exampleDotCom = "http://example.com/"
val subfileName = "sitemapfilespec"
var xml: Elem = _
before {
val tempFile = File.createTempFile(subfileName, "")
val sitemap = createSitemap(exampleDotCom, List(tempFile).iterator, timestamp, tempFile.getParentFile)
xml = XML.loadFile(sitemap)
}
"A Sitemap" should "be a well-formed xml file" in {
assert(xml.nonEmpty)
}
it should "have a root element <sitemapindex> in the correct namespace" in {
assert("sitemapindex".equals(xml.label))
assert(sitemapNS.equals(xml.namespace))
}
it should "have children elements <sitemap>" in {
assert((xml \ "sitemap").nonEmpty)
}
it should "have <loc> and <lastmod> elements inside each <sitemap>" in {
(xml \\ "sitemap").foreach(sitemap => {
assert((sitemap \ "loc").size == 1)
assert((sitemap \ "lastmod").size == 1)
})
}
it should "have <lastmod> elements with valid timestamps" in {
(xml \\ "lastmod").foreach(lastmod => {
assert(timestamp.equals(lastmod.text))
})
}
it should "have <loc> elements with valid URLs" in {
(xml \\ "loc").foreach(loc => {
assert("example.com".equals(new URL(loc.text).getHost))
})
}
}