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

Scala NodeSeq类代码示例

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

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



在下文中一共展示了NodeSeq类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: TrainPage

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

import scala.util.Try
import scala.xml.{NodeSeq, Text}

case class TrainPage(
  name: String,
  number: String,
  code: Option[Int],
  stops: List[StopDetail],
  url: String,
  car: List[String],
  remark: List[String],
  day: String
)

object TrainPage {
  import utils.ParseHelper._

  def fromXML(xml: NodeSeq, url: String): Either[String, TrainPage] = {
    import utils.EitherUtil.eitherToRightProjection
    for {
      container <- (xml \\ "div" find (_ \ "@id" contains Text("container02"))).toRight("container")
      table <- (container \\ "table" find (_ \ "@cellpadding" contains Text("5"))).toRight("table")
      trs = table \ "tbody" \ "tr"
      name <- extractValueFromTr(trs, 0)(norm).toRight("name")
      number <- extractValueFromTr(trs, 1)(norm).toRight("number")
      code = extractValueFromTr(trs, 2)(norm).flatMap { it => Try(it.toInt).toOption }
      car <- extractValueFromTr(trs, 3)(normList(',')).toRight("car")
      remark <- extractValueFromTr(trs, 4)(normList(',')).toRight("remark")
      day <- extractValueFromTr(trs, 5)(norm).toRight("day")
      stops = trs.view(8, trs.length).flatMap(StopDetail.fromXML).toList
    } yield { TrainPage(name.replace(norm("?"), "?"), number, code, stops, url, car, remark, day) }
  }

  private def extractValueFromTr[A](xml: NodeSeq, index: Int)(f: String => A): Option[A] = for {
    line <- xml.lift(index)
    raw <- (line \ "td").lift(1)
  } yield f((raw \ "span").text)
} 
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:41,代码来源:TrainPage.scala


示例2: streamlinedXmlEquality

//设置package包名称以及导入依赖的类
package fr.ramiro.scala.dom

import scala.xml.NodeSeq
import org.scalactic.{ Equality, Uniformity }

trait StreamlinedXmlEquality {
  implicit def streamlinedXmlEquality[T <: NodeSeq]: Equality[T] = {
    new Equality[T] {
      val xu: Uniformity[T] = StreamlinedXml.streamlined[T]
      def areEqual(a: T, b: Any): Boolean = {
        xu.normalized(a) == xu.normalizedOrSame(b)
      }
    }
  }
}

object StreamlinedXmlEquality extends StreamlinedXmlEquality 
开发者ID:rrramiro,项目名称:scala-dom,代码行数:18,代码来源:StreamlinedXmlEquality.scala


示例3: Helpers

//设置package包名称以及导入依赖的类
import sbt._
import sbt.Keys._

import scala.xml.{Comment, Elem, Node, NodeSeq}
import scala.xml.transform.{RewriteRule, RuleTransformer}

object Helpers {

  def dropIfDependency(node: Node): Node = {
      new RuleTransformer(new RewriteRule {
        override def transform(node: Node): NodeSeq = node match {
          case e: Elem if e.label == "dependency" => NodeSeq.Empty
          case _ => node
        }
      }).transform(node).head
    }

  def pickFilesFromSubpaths(
      roots: Seq[String],
      subpath: File,
      predicate: String => Boolean): Seq[(File, String)] = {

    roots
      .map(file(_) / subpath.toString)
      .flatMap({ f =>
        Path
          .allSubpaths(f)
          .filter({ case (_, relativePath) => predicate(relativePath) })
          .toSeq
      })
  }
} 
开发者ID:brthanmathwoag,项目名称:jancy,代码行数:33,代码来源:Helpers.scala


示例4: Marshalling

//设置package包名称以及导入依赖的类
package akka.stream.alpakka.s3.impl

import java.time.Instant

import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport
import akka.http.scaladsl.model.{ContentTypes, HttpCharsets, MediaTypes}
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}
import akka.stream.alpakka.s3.scaladsl.ListBucketResultContents

import scala.xml.NodeSeq

private[alpakka] object Marshalling {
  import ScalaXmlSupport._

  implicit val multipartUploadUnmarshaller: FromEntityUnmarshaller[MultipartUpload] = {
    nodeSeqUnmarshaller(ContentTypes.`application/octet-stream`) map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        MultipartUpload(S3Location((x \ "Bucket").text, (x \ "Key").text), (x \ "UploadId").text)
    }
  }

  implicit val completeMultipartUploadResultUnmarshaller: FromEntityUnmarshaller[CompleteMultipartUploadResult] = {
    nodeSeqUnmarshaller(MediaTypes.`application/xml` withCharset HttpCharsets.`UTF-8`) map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        CompleteMultipartUploadResult(
          (x \ "Location").text,
          (x \ "Bucket").text,
          (x \ "Key").text,
          (x \ "ETag").text.drop(1).dropRight(1)
        )
    }
  }

  val isTruncated = "IsTruncated"
  val continuationToken = "NextContinuationToken"

  implicit val listBucketResultUnmarshaller: FromEntityUnmarshaller[ListBucketResult] = {
    nodeSeqUnmarshaller(MediaTypes.`application/xml` withCharset HttpCharsets.`UTF-8`).map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        ListBucketResult(
          (x \ isTruncated).text == "true",
          Some(x \ continuationToken).filter(_.nonEmpty).map(_.text),
          (x \\ "Contents").map { c =>
            ListBucketResultContents(
              (x \ "Name").text,
              (c \ "Key").text,
              (c \ "ETag").text.drop(1).dropRight(1),
              (c \ "Size").text.toLong,
              Instant.parse((c \ "LastModified").text),
              (c \ "StorageClass").text
            )
          }
        )
    }
  }
} 
开发者ID:akka,项目名称:alpakka,代码行数:60,代码来源:Marshalling.scala


示例5: ConverterUtils

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

import scala.concurrent.{ExecutionContext, Future}
import scala.xml.NodeSeq
import org.joda.time.DateTime

object ConverterUtils {

  def stringToDate(s: String, pattern: String): Option[DateTime] = {
    scala.util.Try(DateUtils.stringToDate(s, pattern)).toOption
  }

  def stringToInt(s: String): Option[Int] = {
    if (s == "inf") {
      Some(Integer.MAX_VALUE)
    } else {
      scala.util.Try(s.toInt).toOption
    }
  }

  def prettyPrintXml(xml: NodeSeq) = {
    val printer = new scala.xml.PrettyPrinter(80, 2)
    xml.toList.map(_.toString).fold("")((x, y) => x + y)
  }

  def scalaMapToJavaMap[A, B](smap: Map[A, B]): java.util.Map[A, B] = {
    val jmap = new java.util.HashMap[A, B]
    smap.foreach(p => jmap.put(p._1, p._2.asInstanceOf[B]))

    jmap
  }

  def transform[A](o: Option[Future[A]])(implicit exec: ExecutionContext): Future[Option[A]] =
    o.map(f => f.map(Option(_))).getOrElse(Future.successful(None))
} 
开发者ID:Driox,项目名称:play-app-seed,代码行数:36,代码来源:ConverterUtils.scala


示例6: whenDefined

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

import java.io.InputStream

import com.scalawilliam.xs4s.elementprocessor.XmlStreamElementProcessor

import scala.xml.{Elem, NodeSeq}


trait XmlBasedParser {
  def whenDefined(parameter: NodeSeq): Option[String] = {
    val text: String = parameter.text
    if (text.isEmpty) {
      None
    } else {
      Some(text)
    }
  }

  def getElementsWithNameFromInputStream(
      ElementName: String, is: InputStream): Iterator[Elem] = {
    val trkptSplitter = XmlStreamElementProcessor.collectElements(
        _.lastOption.contains(ElementName))
    import XmlStreamElementProcessor.IteratorCreator._
    trkptSplitter.processInputStream(is)
  }
} 
开发者ID:shiptrail,项目名称:be-be-main,代码行数:28,代码来源:XmlBasedParser.scala


示例7: StopDetail

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

import scala.xml.NodeSeq
import scala.collection.breakOut

case class StopDetail(
  name: String,
  url: String,
  code: Option[Int],
  no: Option[String],
  departure: TrainRun,
  arrive: TrainRun
)

object StopDetail {
  import utils.ParseHelper._

  val ReCode = """\((\d+)\)""".r

  def fromXML(xml: NodeSeq): Option[StopDetail] = {
    val tds: Seq[String] = (xml \ "td").map { elem => (elem \ "span").text }(breakOut)
    for {
      url <- (xml \\ "a" \ "@href").headOption
      sta <- tds.lift(0)
      stop <- tds.lift(1)
      xs = normList('\n')(sta)
      ys = normList('\n')(stop)
      if 2 <= ys.length && 1 <= xs.length
      name = xs.head
      code = xs.lift(1).flatMap(ReCode.findFirstMatchIn(_)).map(_.group(1).toInt)
      Seq(arr, dep) = ys.map(TrainRun.fromString)
      no = tds.lift(2).map(norm).filter(_.nonEmpty)
    } yield StopDetail(name, normURL(url.text), code, no, dep, arr)
  }

  def normURL(url: String) = url.replace("../../", "/newdata/station/")
}

sealed abstract class TrainRun

object TrainRun {
  val ReTime = """(\d\d)\:(\d\d).*""".r
  case class Time(hour: Int, minutes: Int) extends TrainRun
  case object Pass extends TrainRun
  case object NotService extends TrainRun

  def fromString(str: String): TrainRun =
    str match {
      case "?" => Pass
      case ReTime(hour, minutes) => Time(hour.toInt, minutes.toInt)
      case _ => NotService
    }
} 
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:54,代码来源:StopDetail.scala


示例8: MonthCalendar

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

import kippercalendar.Calendar._
import kippercalendar.Clock._
import net.liftweb.http.SHtml
import net.liftweb.http.js.JsCmds._
import org.joda.time.Interval

import scala.xml.NodeSeq

object MonthCalendar {

  val previousMonthButtonId = "previousMonthButtonId"
  val nextMonthButtonId = "nextMonthButtonId"
  val monthTitleId = "monthTitleId"

  def apply(monthInterval: Interval): NodeSeq = {
    <h3>
      <span id={monthTitleId}>{title(monthInterval)}</span>
      {monthDayNavigationButtons(monthInterval, monthActive = true)}
    </h3> ++
    previousMonthButton(monthInterval) ++
    nextMonthButton(monthInterval)
  }

  def title(monthInterval: Interval) = monthInterval.getStart.getYear.toString + " " + monthFull(monthInterval.getStart)

  private def previousMonthButton(monthInterval: Interval) =
    SHtml.ajaxButton("< previous month", () ? SetHtml(kipperCalendarContainerId, MonthCalendar(new Interval(monthInterval.getStart.minusMonths(1), monthInterval.getEnd.minusMonths(1)))), "id" ? previousMonthButtonId, "class" ? "col-lg-2 btn btn-primary")

  private def nextMonthButton(monthInterval: Interval) =
    SHtml.ajaxButton("next month >", () ? SetHtml(kipperCalendarContainerId, MonthCalendar(new Interval(monthInterval.getStart.plusMonths(1), monthInterval.getEnd.plusMonths(1)))), "id" ? nextMonthButtonId, "class" ? "col-lg-2 col-lg-offset-8  btn btn-primary")

} 
开发者ID:kipperjim,项目名称:kipper-calendar,代码行数:35,代码来源:MonthCalendar.scala


示例9: DayCalendar

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

import kippercalendar.Calendar._
import kippercalendar.Clock._
import net.liftweb.http.SHtml
import net.liftweb.http.js.JsCmds.SetHtml
import org.joda.time.Interval

import scala.xml.NodeSeq

object DayCalendar {

  val previousDayButtonId = "previousDayButtonId"
  val nextDayButtonId = "nextDayButtonId"
  val dayTitleId = "dayTitleId"

  def apply(day: Interval): NodeSeq =
    <h3>
      <span id={dayTitleId}>{title(day)}</span>
      {monthDayNavigationButtons(day, monthActive = false)}
    </h3> ++
      previousDayButton(day) ++
      nextDayButton(day)

  def title(day: Interval) = dayOfTheWeekAndMonth(day.getStart) + " " + monthFull(day.getStart) + " " + day.getStart.getYear

  private def previousDayButton(monthInterval: Interval) =
    SHtml.ajaxButton("< previous day", () ? SetHtml(kipperCalendarContainerId, DayCalendar(new Interval(monthInterval.getStart.minusDays(1), monthInterval.getEnd.minusDays(1)))), "id" ? previousDayButtonId, "class" ? "col-lg-2 btn btn-primary")

  private def nextDayButton(monthInterval: Interval) =
    SHtml.ajaxButton("next day >", () ? SetHtml(kipperCalendarContainerId, DayCalendar(new Interval(monthInterval.getStart.plusDays(1), monthInterval.getEnd.plusDays(1)))), "id" ? nextDayButtonId, "class" ? "col-lg-2 col-lg-offset-8  btn btn-primary")
} 
开发者ID:kipperjim,项目名称:kipper-calendar,代码行数:33,代码来源:DayCalendar.scala


示例10: DocxMetadataWriter

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

import java.security.MessageDigest
import javax.xml.bind.DatatypeConverter

import anchorman.core.Document
import anchorman.media._

import scala.xml.NodeSeq

class DocxMetadataWriter {
  val documentRelId: String =
    "rDocument"

  val numberingRelId: String =
    "rNumbering"

  val stylesRelId: String =
    "rStyles"

  def mediaRelId(url: String): String = {
    val digest = MessageDigest.getInstance("MD5")
    digest.update(url.getBytes)
    "rMedia" + DatatypeConverter.printHexBinary(digest.digest()).toUpperCase
  }

  def writeContentTypes(doc: Document): NodeSeq =
    <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
      <Default ContentType="application/xml" Extension="xml"/>
      <Default ContentType="image/jpeg" Extension="jpg"/>
      <Default ContentType="image/png" Extension="png"/>
      <Default ContentType="image/x-emf" Extension="emf"/>
      <Default ContentType="application/vnd.openxmlformats-package.relationships+xml" Extension="rels"/>
      <Override ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml" PartName="/word/document.xml"/>
      <Override ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml" PartName="/word/numbering.xml"/>
      <Override ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml" PartName="/word/styles.xml"/>
    </Types>

  def writeRootRels(doc: Document): NodeSeq =
    <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
      <Relationship Id={documentRelId} Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
    </Relationships>

  def writeDocumentRels(doc: Document, media: Seq[MediaFile]): NodeSeq = {
    <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
      <Relationship Id={numberingRelId} Target="numbering.xml" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering"/>
      <Relationship Id={stylesRelId} Target="styles.xml" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"/>
      {
        media.map { file =>
          <Relationship Id={file.relId} Target={"media/" + file.filename} Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"/>
        }
      }
    </Relationships>
  }
} 
开发者ID:davegurnell,项目名称:anchorman,代码行数:56,代码来源:DocxMetadataWriter.scala


示例11: 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


示例12: 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


示例13: OrderCalculatorXMLServer

//设置package包名称以及导入依赖的类
package com.packt.chapter9

import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.HttpApp
import akka.http.scaladsl.settings.ServerSettings
import com.typesafe.config.ConfigFactory

import scala.util.Random._
import scala.xml.NodeSeq

object OrderCalculatorXMLServer extends HttpApp with OrderXmlSupport {

  val route =
    path("calculateGrandTotal" ~ Slash.?) {
      post {
        entity(as[NodeSeq]) { xmlOrder =>
          complete {
            calculateGrandTotal(xmlOrder)
          }
        }
      }
    } ~
      path("randomOrder") {
        get {
          complete {
            generateRandomOrder()
          }
        }
      }

  private def calculateGrandTotal(o: Order) : NodeSeq = {
    val amount = o.items.map(i => i.percentageDiscount.getOrElse(1.0d) * i.unitPrice * i.quantity).sum + o.deliveryPrice
    GrandTotal(o.id, amount)
  }

  private def generateRandomOrder(): NodeSeq = {
    val items = (0 to nextInt(5)).map(i => {
      Item(i, nextInt(100), 100 * nextDouble(), if (nextBoolean()) Some(nextDouble()) else None)
    }).toList
    Order(nextString(4), System.currentTimeMillis(), items, 100 * nextDouble(), Map("notes" -> "random"))
  }
}

object OrderCalculatorXMLServerApplication extends App {
  OrderCalculatorXMLServer.startServer("0.0.0.0", 8088, ServerSettings(ConfigFactory.load))
} 
开发者ID:PacktPublishing,项目名称:Akka-Cookbook,代码行数:47,代码来源:OrderCalculatorXMLServer.scala


示例14: apply

//设置package包名称以及导入依赖的类
package com.jensraaby.sxt.decoding

import scala.xml.NodeSeq

trait XmlDecoder[A] {
  def apply(node: NodeSeq): XmlDecoder.Result[A]

}

final object XmlDecoder {
  type Result[A] = Either[XmlDecodingFailure, A]

  implicit object StringDecoder extends XmlDecoder[String] {
    override def apply(node: NodeSeq): Result[String] = node.text match {
      case "" => Left(XmlDecodingFailure(s"No text in input: $node"))
      case text => Right(text)
    }
  }

  implicit def optionDecoder[A: XmlDecoder]: XmlDecoder[Option[A]] = new XmlDecoder[Option[A]] {
    private val aDecoder = implicitly[XmlDecoder[A]]
    override def apply(node: NodeSeq) = Right(aDecoder(node).toOption)
  }

  implicit def listDecoder[A: XmlDecoder]: XmlDecoder[List[A]] = new XmlDecoder[List[A]] {
    private val aDecoder = implicitly[XmlDecoder[A]]
    import cats.implicits._
    override def apply(node: NodeSeq) = node.map(aDecoder.apply).toList.sequenceU
  }
} 
开发者ID:jensraaby,项目名称:SXT,代码行数:31,代码来源:XmlDecoder.scala


示例15: Marshalling

//设置package包名称以及导入依赖的类
package com.bluelabs.s3stream

import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport
import akka.http.scaladsl.model.{ContentTypes, HttpCharsets, MediaTypes}
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}

import scala.xml.NodeSeq

object Marshalling {
  import ScalaXmlSupport._

  implicit val MultipartUploadUnmarshaller: FromEntityUnmarshaller[MultipartUpload] = {
    nodeSeqUnmarshaller(ContentTypes.`application/octet-stream`) map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x             =>
        MultipartUpload(S3Location((x \ "Bucket").text, (x \ "Key").text), (x \ "UploadId").text)
    }
  }

  implicit val completeMultipartUploadResultUnmarshaller: FromEntityUnmarshaller[CompleteMultipartUploadResult] = {
    nodeSeqUnmarshaller(MediaTypes.`application/xml` withCharset HttpCharsets.`UTF-8`) map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        CompleteMultipartUploadResult(
          (x \ "Location").text,
          (x \ "Bucket").text, (x \ "Key").text,
          (x \ "Etag").text
        )
    }
  }
} 
开发者ID:bluelabsio,项目名称:s3-stream,代码行数:32,代码来源:Marshalling.scala


示例16: ChapterFeed

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

import java.text.SimpleDateFormat
import java.util.{Date, Locale}

import scala.collection.immutable.Seq
import scala.xml.{Elem, Node, NodeSeq, XML}



case class ChapterFeed(title: String, link: String, description: String, publicationDate: Date) {
  val chapterNumPattern = "(\\s(\\w|\\.)+$|(\\s\\d+\\s\\/\\s\\d+))".r
  def extractTitleAndNumber: (String, String) = {
    chapterNumPattern findFirstIn title
      match {
      case Some(num) => (title replaceAll(num, ""), num.drop(1))
      case None => (title, "Num not found")
    }
  }
}

class RSSReader {
  val rssDatePattern = "EEE, dd MMM yyyy HH:mm:ss zzz"
  val xml: Elem = XML.load("http://mangastream.com/rss")

  def getChaptersFromRss: Seq[ChapterFeed] = {
    val sdf = new SimpleDateFormat(rssDatePattern, Locale.ENGLISH)
    val items: NodeSeq = xml \\ "item"
    items.map(node => withChapterConverter(sdf, node))
  }

  def withChapterConverter(sdf: SimpleDateFormat,node: Node):
    ChapterFeed = ChapterFeed(title = (node \\ "title").text,
      link = (node \\ "link").text,
      description = (node \\ "description").text,
      publicationDate = sdf.parse((node \\ "pubDate").text))
} 
开发者ID:LeonardoZ,项目名称:scrapms,代码行数:38,代码来源:RSSReader.scala


示例17: whenDefined

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

import java.io.InputStream
import com.scalawilliam.xs4s.elementprocessor.XmlStreamElementProcessor
import scala.xml.{Elem, NodeSeq}


trait XmlBasedParser {
  def whenDefined(parameter: NodeSeq): Option[String] = {
    val text: String = parameter.text
    if (text.isEmpty) {
      None
    } else {
      Some(text)
    }
  }

  def getElementsWithNameFromInputStream(ElementName: String, is: InputStream): Iterator[Elem] = {
    val trkptSplitter = XmlStreamElementProcessor.collectElements(_.lastOption.contains(ElementName))
    import XmlStreamElementProcessor.IteratorCreator._
    trkptSplitter.processInputStream(is)
  }
} 
开发者ID:shiptrail,项目名称:qa-influx-simulator,代码行数:24,代码来源:XmlBasedParser.scala


示例18: ProfileSnippet

//设置package包名称以及导入依赖的类
package com.fustigatedcat.heystk.ui.snippet

import com.fustigatedcat.heystk.ui.dao.UserDAO
import net.liftweb.http.{SHtml, S}
import net.liftweb.http.js.{JsCmd, JsCmds, JE}
import net.liftweb.http.js.JE.{JsVar, Stringify, JsObj}
import net.liftweb.json._
import net.liftweb.util._, Helpers._

import scala.xml.NodeSeq

object ProfileSnippet {

  implicit val formats = net.liftweb.json.DefaultFormats

  def getLoggedInUser() : CssSel = "*" #> S.attr("callback").map(callback => {
    def _getLoggedInUser() : JsCmd = {
      LoggedInUser.is.map(user => {
        JE.Call(
          callback,
          JsObj(
            "username" -> user.username,
            "firstName" -> user.firstName,
            "lastName" -> user.lastName
          )
        ).cmd
      }).getOrElse(JsCmds.Alert("Non-Existent User"))
    }
    JsCmds.Script(
      JsCmds.Function(
        "getLoggedInUser",
        List(),
        SHtml.ajaxInvoke(_getLoggedInUser).cmd
      )
    )
  }).getOrElse(NodeSeq.Empty)

  def updateUser() : CssSel = "*" #> {
    def _updateUser(in : String) : JsCmd = {
      LoggedInUser.is.map(user => parseOpt(in).map(js => {
        UserDAO.updateUser(
          user,
          (js \ "firstName").extract[String],
          (js \ "lastName").extract[String],
          (js \ "password").extractOpt[String]
        )
        S.redirectTo("/")
      }).getOrElse(JsCmds.Alert("Invalid Input"))
      ).getOrElse(JsCmds.Alert("Non-Existent User"))
    }
    JsCmds.Script(
      JsCmds.Function(
        "updateUser",
        List("user"),
        SHtml.ajaxCall(Stringify(JsVar("user")), _updateUser).cmd
      )
    )
  }

} 
开发者ID:fustigatedcat,项目名称:heystk,代码行数:61,代码来源:ProfileSnippet.scala


示例19: LoggedInUser

//设置package包名称以及导入依赖的类
package com.fustigatedcat.heystk.ui.snippet

import com.fustigatedcat.heystk.ui.dao.UserDAO
import com.fustigatedcat.heystk.ui.model.User
import net.liftweb.common.Full
import net.liftweb.http.{SessionVar, S}

import scala.xml.NodeSeq

object LoggedInUser extends SessionVar[Option[User]](None)

object Login {

  def login(xhtml : NodeSeq): NodeSeq = if(S.post_?) {
    (S.param("username"), S.param("password")) match {
      case (Full(username), Full(password)) => UserDAO.authenticateUser(username, password).map(u => {
        LoggedInUser(Some(u))
        S.redirectTo("/")
      }).getOrElse(xhtml)
      case _ => xhtml
    }
  } else {
    NodeSeq.Empty
  }

  def logout() = {
    LoggedInUser(None)
    S.session.foreach(_.destroySession())
    S.redirectTo("/login")
  }

} 
开发者ID:fustigatedcat,项目名称:heystk,代码行数:33,代码来源:Login.scala


示例20: UnlabeledPoolCache

//设置package包名称以及导入依赖的类
package de.fuberlin.wiwiss.silk.workspace.modules.linking

import de.fuberlin.wiwiss.silk.entity.{EntityDescription, Link}
import de.fuberlin.wiwiss.silk.workspace.Project
import scala.xml.{Node, NodeSeq}
import de.fuberlin.wiwiss.silk.util.DPair
import de.fuberlin.wiwiss.silk.workspace.modules.Cache

class UnlabeledPoolCache extends Cache[LinkingTask, Seq[Link]](Seq.empty) {

  
  override def update(project: Project, task: LinkingTask) {

  }

  override def toXML: NodeSeq = {
    <Pool> { for(link <- value) yield link.toXML } </Pool>
  }

  override def loadFromXML(node: Node) {
//    value =
//      for(linkNode <- node \ "Pool" \ "Link") yield {
//        Link.fromXML(linkNode)
//      }
    ???
  }
} 
开发者ID:petrovskip,项目名称:silk.2.6-GenLinkSA,代码行数:28,代码来源:UnlabeledPoolCache.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala Map类代码示例发布时间:2022-05-23
下一篇:
Scala Callable类代码示例发布时间: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