• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala XML类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中scala.xml.XML的典型用法代码示例。如果您正苦于以下问题:Scala XML类的具体用法?Scala XML怎么用?Scala XML使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了XML类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
  }
} 
开发者ID:telegraph,项目名称:sbt-wiremock,代码行数:62,代码来源:ModuleResolver.scala


示例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)
    }
  }

} 
开发者ID:kotarohara,项目名称:ToSidewalk,代码行数:50,代码来源:OSMParser.scala


示例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
    )
  }
} 
开发者ID:YoshinoriN,项目名称:gitbucket-monitoring-plugin,代码行数:59,代码来源:LogBack.scala


示例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(",")
    )
  }
} 
开发者ID:mendozagabe1618,项目名称:openhub-source-search-engine,代码行数:35,代码来源:OpenHubMetadataFetcher.scala


示例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
  }
} 
开发者ID:PrawoPolskie,项目名称:toakoma,代码行数:56,代码来源:Img2TxtProcessor.scala


示例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")
	}
} 
开发者ID:Takeuchi-Lab-LM,项目名称:scala_asa3,代码行数:28,代码来源:convertDict.scala


示例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))
  }
} 
开发者ID:Spielekreis-Darmstadt,项目名称:lending,代码行数:43,代码来源:ConnectionProperties.scala


示例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
    }
} 
开发者ID:jkraml,项目名称:gpsplot,代码行数:45,代码来源:GpxFileReader.scala


示例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()

} 
开发者ID:greg2010,项目名称:pizza-eveapi-mirror,代码行数:52,代码来源:EndpointsSpec.scala


示例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]]
} 
开发者ID:daviddenton,项目名称:finagle-aws,代码行数:45,代码来源:S3Api.scala


示例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
  }
} 
开发者ID:note,项目名称:xml-lens,代码行数:40,代码来源:SimpleTransformationStd.scala


示例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
  }

} 
开发者ID:note,项目名称:xml-lens,代码行数:42,代码来源:PrintBench.scala


示例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()
    }
  }
} 
开发者ID:davegurnell,项目名称:anchorman,代码行数:27,代码来源:ZipImplicits.scala


示例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 \ "_"
} 
开发者ID:scalahub,项目名称:acc,代码行数:60,代码来源:Util.scala


示例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))
    })
  }
} 
开发者ID:dpla,项目名称:sitemap,代码行数:54,代码来源:SitemapFileSpec.scala


示例16: Execute

//设置package包名称以及导入依赖的类
package eveapi

import argonaut.{CursorHistory, Parse}
import org.atnos.eff.StateEffect
import scalaz._, Scalaz._
import scalaz.concurrent._
import org.http4s._
import org.http4s.argonaut._
import scala.xml.XML

import eveapi.oauth._
import eveapi.utils.TaskEffect._

object Execute {
  import OAuth2._
  val OAuthInterpreter = new (Lift.Link ~> Api) {
    def apply[T](l: Lift.Link[T]) = l match {
      case Lift.Get(link, dec) => fetch(Request(uri = link.href, method = Method.GET))(dec)
      case Lift.Put(link, value, dec, enc) =>
        fetch(Request(uri = link.href, method = Method.PUT).withBody(enc.encode(value)))(dec)
      case Lift.Post(link, value, dec, enc) =>
        fetch(Request(uri = link.href, method = Method.POST).withBody(enc.encode(value)))(dec)
      case Lift.Delete(link, dec) =>
        fetch(Request(uri = link.href, method = Method.DELETE))(dec)
      case Lift.GetXML(link, dec) =>
        fetchXML(link.href)(dec)
    }
  }

  
  def localInterpreter(values: Uri => String) =
    new (Lift.Link ~> Either[Either[String, (String, CursorHistory)], ?]) {
      def apply[T](l: Lift.Link[T]) = l match {
        case Lift.Get(link, dec) => Parse.decode(values(link.href))(dec)
        case Lift.Put(link, _, dec, _) => Parse.decode(values(link.href))(dec)
        case Lift.Post(link, _, dec, _) => Parse.decode(values(link.href))(dec)
        case Lift.Delete(link, dec) => Parse.decode(values(link.href))(dec)
        case Lift.GetXML(link, dec) =>
          Right(scalaxb.fromXML[T](XML.loadString(values(link.href)))(dec))
      }
    }
} 
开发者ID:scala-eveapi,项目名称:eveapi,代码行数:43,代码来源:execute.scala


示例17: DoiMetaSerializerTest

//设置package包名称以及导入依赖的类
package se.lu.nateko.cp.doi.core.test

import org.scalatest.FunSuite
import views.xml.doi.DoiMeta
import scala.xml.XML
import se.lu.nateko.cp.doi.core.DoiMetaParser
import javax.xml.validation.SchemaFactory
import javax.xml.XMLConstants
import java.net.URL
import javax.xml.transform.stream.StreamSource
import java.io.StringReader

class DoiMetaSerializerTest extends FunSuite{

	test("Serializing/parsing round trip"){
		val meta = DoiMetaExamples.full

		assertResult(meta){
			val serialized = views.xml.doi.DoiMeta(meta).body
			val xml = XML.loadString(serialized)
			DoiMetaParser.parse(xml).get
		}
	}

	ignore("For manual run: validating the XML-serialized metadata against DataCite's XSD Schema"){
		val sfactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
		val schema = sfactory.newSchema(new URL("http://schema.datacite.org/meta/kernel-4.0/metadata.xsd"))
		val validator = schema.newValidator()
		val serialized = views.xml.doi.DoiMeta(DoiMetaExamples.full).body
		val source = new StreamSource(new StringReader(serialized))
		validator.validate(source)
	}
} 
开发者ID:ICOS-Carbon-Portal,项目名称:doi,代码行数:34,代码来源:DoiMetaSerializerTest.scala


示例18: fetchXML

//设置package包名称以及导入依赖的类
import java.net.URL
import scala.io.Source.fromURL
import io.circe._
import io.circe.parser._
import scala.io.Source
import scala.xml.{Elem, Node, XML}

package object  rss {

  System.setProperty("http.agent", "my rss podcast downloader - jarrodwb.com")

  def fetchXML(url: String): Elem = XML.loadString(Source.fromURL(url).mkString)

  def getItems(xml: Node) = (xml \ "channel" \ "item" \ "enclosure").map( _ \ "@url").map(_.text).toList

  def iTunesFlipper(url: String) = {

    case class ID(value: String)

    def fromITunes(url: String): ID = {
      val myURL = new URL(url)
      ID(myURL.getPath.split("/").last.drop(2))
    }

    def lookup(id: ID): URL = {
      val query = s"https://itunes.apple.com/lookup?id=${id.value}&entity=podcast"
      val json = parse(fromURL(new URL(query)).mkString).getOrElse(Json.Null)
      val hc = json.hcursor
      val urlEither = hc.downField("results").downArray.downField("feedUrl").as[String]
      urlEither match {
        case Right(url) => new URL(url)
        case Left(error) => throw error
      }
    }

    (fromITunes _ andThen lookup)(url)

  }

  def allDownloadURLs(urls: List[String]) = urls map fetchXML flatMap getItems

} 
开发者ID:jarrodwb,项目名称:rss,代码行数:43,代码来源:package.scala


示例19: xml

//设置package包名称以及导入依赖的类
package io.rout.generic

import cats.data.Xor
import com.twitter.io.Buf
import com.twitter.util.Try
import io.rout.{Decode, Encode, Error}
import io.rout.parse.xml._
import shapeless._
import scala.xml.XML

object xml {

object semiauto {

  class Encoder[T]{
    def encodeXml(implicit toXml: ToXml[T]): Encode.ApplicationXml[T] = Encode.xml(t =>
      Buf.Utf8(toXml.toXml(t).toString()))

    def derive[LKV](implicit
      gen:LabelledGeneric.Aux[T,LKV],
      toXml: Lazy[ToXml.Wrap[LKV]]
    ): ToXml[T] = ToXml.deriveInstance(gen,toXml)
  }

  class Decoder[T]{
     def decodeXml(implicit fromXml: FromXml[T]): Decode.ApplicationXml[String,T] = Decode.applicationXml(i =>
      fromXml.fromXml(XML.loadString(i)).fold[Xor[Error,Try[T]]](
        err => Xor.Left(Error(err.getMessage)),
        value => Xor.Right(Try(value))
      ))

   def derive[LKV](implicit
    gen:LabelledGeneric.Aux[T,LKV],
    fromXml: Lazy[FromXml.Wrap[LKV]]
  ): FromXml[T] = FromXml.deriveInstance(gen,fromXml)

  }

  def decode[T] = new Decoder[T]

  def encode[T] = new Encoder[T]
}

} 
开发者ID:teodimoff,项目名称:rOut,代码行数:45,代码来源:xml.scala


示例20: JsonUtils

//设置package包名称以及导入依赖的类
package beam.utils

import beam.router.RoutingModel.{BeamGraphPath, BeamLeg}
import io.circe.{Encoder, Json, JsonObject}
import org.matsim.api.core.v01.Coord
import org.matsim.core.utils.io.IOUtils
import io.circe.syntax._
import scala.xml.XML


object JsonUtils {

  // Put global implicit encoders here. Can import wholesale in implementing code.
  object syntax {
    implicit val encodeLeg: Encoder[BeamLeg] = (a: BeamLeg) => {
      val jsonBuilder: Map[String, Json] = Map(
        "typ" -> Json.fromString("trajectory"), "mode" -> a.mode.asJson, "shp" -> a.graphPath.asJson)
      Json.fromJsonObject(JsonObject.fromMap(jsonBuilder))
    }

    implicit val encodeCoord: Encoder[Coord]=(a:Coord)=>{
      Json.fromValues(Seq(Json.fromDoubleOrNull(MathUtils.roundDouble(a.getX,5)),Json.fromDoubleOrNull(MathUtils.roundDouble(a.getY,5))))
    }
  }

  def processEventsFileVizData(inFile: String, outFile: String): Unit = {
    val xml = XML.load(IOUtils.getInputStream(inFile))
    val events = xml \\ "events" \ "event"
    val out = for {event <- events if event.attribute("type").get.toString() == "pathTraversal" | event.attribute("type").get.toString() == "pointProcess"
    } yield event.attribute("viz_data").get.toString().replace("&quot;", "\"")
    val jsonOutString = out.mkString("\n[", ",\n", "]\n")
    val writer = IOUtils.getBufferedWriter(outFile)
    writer.write(jsonOutString)
    writer.flush()
    writer.close()
  }

  //// Private Methods

  private[this] implicit val encodeGraphPath: Encoder[BeamGraphPath] = (a: BeamGraphPath) => {
    Json.fromValues(a.trajectory.map(_.asJson))
  }


  //~
} 
开发者ID:LBNL-UCB-STI,项目名称:beam,代码行数:47,代码来源:JsonUtils.scala



注:本文中的scala.xml.XML类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala SbtGitVersioning类代码示例发布时间:2022-05-23
下一篇:
Scala Environment类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap