本文整理汇总了Scala中scala.xml.NodeSeq类的典型用法代码示例。如果您正苦于以下问题:Scala NodeSeq类的具体用法?Scala NodeSeq怎么用?Scala NodeSeq使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了NodeSeq类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
}
示例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
示例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
})
}
}
示例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
)
}
)
}
}
}
示例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))
}
示例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)
}
}
示例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
}
}
示例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")
}
示例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")
}
示例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>
}
}
示例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()
}
}
}
示例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 \ "_"
}
示例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))
}
示例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
}
}
示例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
)
}
}
}