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

Scala Elem类代码示例

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

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



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

示例1: XML

//设置package包名称以及导入依赖的类
package org.cg.scala.dhc.util

import java.io.{ByteArrayOutputStream, File, FileInputStream}

import scala.util.matching.Regex
import scala.xml.Elem
import scala.xml.factory.XMLLoader
import javax.xml.parsers.SAXParser

object XML extends XMLLoader[Elem] {
  override def parser: SAXParser = {
    val f = javax.xml.parsers.SAXParserFactory.newInstance()
    f.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    f.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    f.newSAXParser()
  }
}

object FileUtil {

  def recursiveListFileInfos(baseDir: String, regex: String): Array[FileInfo] =
    recursiveListFiles(baseDir, regex).map(f => new FileInfo(f.getName, f.getCanonicalPath, f.lastModified()))

  def recursiveListFiles(baseDir: String, regex: String): Array[File] = recursiveListFiles(new File(baseDir), new Regex(regex))

  def recursiveListFiles(f: File, r: Regex): Array[File] = {
    val these = f.listFiles
    if (these != null) {
      val good = these.filter(f => r.findFirstIn(f.getName).isDefined)
      good ++ these.filter(_.isDirectory).flatMap(recursiveListFiles(_, r))
    }
    else
      new Array[File](0)
  }

  def fileToString(file: File) = {
    val inStream = new FileInputStream(file)
    val outStream = new ByteArrayOutputStream
    try {
      var reading = true
      while (reading) {
        inStream.read() match {
          case -1 => reading = false
          case c => outStream.write(c)
        }
      }
      outStream.flush()
    }
    finally {
      inStream.close()
    }
    new String(outStream.toByteArray())
  }

} 
开发者ID:curiosag,项目名称:datahubchecker,代码行数:56,代码来源:FileUtil.scala


示例2: setDocumentLocator

//设置package包名称以及导入依赖的类
package io.github.nawforce.apexlink.utils

import org.xml.sax.Locator

import scala.collection.mutable
import scala.xml.parsing.NoBindingFactoryAdapter
import scala.xml.{Elem, factory, parsing, _}

trait WithLocation extends NoBindingFactoryAdapter {
  private var locator: org.xml.sax.Locator = _
  private val startLines = mutable.Stack[Int]()

  // Get location
  abstract override def setDocumentLocator(locator: Locator) {
    this.locator = locator
    super.setDocumentLocator(locator)
  }

  abstract override def createNode(pre: String, label: String, attrs: MetaData, scope: NamespaceBinding, children: List[Node]): Elem = (
    super.createNode(pre, label, attrs, scope, children)
      % Attribute("line", Text(startLines.pop.toString), Null)
    )

  abstract override def startElement(uri: scala.Predef.String, _localName: scala.Predef.String, qname: scala.Predef.String, attributes: org.xml.sax.Attributes): scala.Unit = {
    startLines.push(locator.getLineNumber)
    super.startElement(uri, _localName, qname, attributes)
  }
}

object XMLLineLoader extends factory.XMLLoader[Elem] {
  override def adapter = new parsing.NoBindingFactoryAdapter with WithLocation
} 
开发者ID:nawforce,项目名称:ApexLink,代码行数:33,代码来源:XMLLineLoader.scala


示例3: LabelReader

//设置package包名称以及导入依赖的类
package io.github.nawforce.apexlink.metadata

import java.nio.file.Files

import io.github.nawforce.apexlink.utils.{LinkerException, LinkerLog, XMLLineLoader, XMLUtils}

import scala.xml.Elem

class LabelReader extends SymbolReader {

  override def loadSymbols(ctx: SymbolReaderContext): Unit = {
    try {
      val labelsFile = ctx.getBaseDir.resolve("labels").resolve("CustomLabels.labels")
      LinkerLog.pushContext(labelsFile.toString)
      if (Files.exists(labelsFile)) {
        LinkerLog.ifNotLogAndThrow(Files.isRegularFile(labelsFile), 0, "Labels file is not a regular file")
        LinkerLog.ifNotLogAndThrow(Files.isReadable(labelsFile), 0, "Labels file is not readable")

        val root = XMLLineLoader.loadFile(labelsFile.toString)
        XMLUtils.ifNotElemLogAndThrow(root, "CustomLabels")

        root.child.foreach {
          case elem: Elem =>
            XMLUtils.ifNotElemLogAndThrow(elem, "labels")
            Label.create(elem).foreach(l => ctx.addLabel(l))
          case _ =>
        }
      }
    } catch {
      case _: LinkerException => () // Ignore, just used to abort processing
    }
  }
} 
开发者ID:nawforce,项目名称:ApexLink,代码行数:34,代码来源:LabelReader.scala


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


示例5: Players

//设置package包名称以及导入依赖的类
package de.htwg.se.SevenSteps.model.player.mockImpl

import de.htwg.se.SevenSteps.model.player.{IPlayer, IPlayers}

import scala.collection.immutable.Map
import scala.util.{Success, Try}
import scala.xml.Elem

case class Players() extends IPlayers {
  def push(name: String): IPlayers = this
  def pop(): IPlayers = this
  def length: Int = 1
  def updateCurPlayer(player: IPlayer): IPlayers = this
  def next(): IPlayers = this
  def nonEmpty: Boolean = true
  def getCurPlayer: IPlayer = Player()
  def setColors(colors: List[Char]): IPlayers = this
  def setAllStonesTo(num: Int): IPlayers = this
  def apply(i: Int): IPlayer = Player()
  def haveNoStones: Boolean = false
  def getAllPossibleColorsFromAllPlayers: List[Char] = List()
  def reset: IPlayers = this
  def toXML: Vector[Elem] = Vector(<el el=""></el>)

}

case class Player() extends IPlayer {
  def getStoneNumber: Int = 2
  def placeStone(color: Char, height: Int): Try[IPlayer] = Success(this)
  def incPoints(delta: Int): IPlayer = this
  def incColor(color: Char, delta: Int): IPlayer = this
  def name: String = "Hans"
  def points: Int = 10
  def map: Option[Map[String, Double]] = None
  def haveNoStones: Boolean = true
  def toXML: Elem = <el el=""></el>

} 
开发者ID:GrimmT,项目名称:de.htwg.se.SevenSteps,代码行数:39,代码来源:PlayerMock.scala


示例6: GridMock

//设置package包名称以及导入依赖的类
package de.htwg.se.SevenSteps.model.grid.mockImpl

import de.htwg.se.SevenSteps.model.grid.{ICell, IGrid}

import scala.util._
import scala.xml.Elem

case class GridMock() extends IGrid {
  def set(row: Int, col: Int, color: Char): IGrid = this
  def set(row: Int, col: Int, height: Int): IGrid = this
  def cell(row: Int, col: Int): Try[ICell] = Success(new CellMock)
  def nonEmpty: Boolean = false
  def getColors: List[Char] = List('b','b','b','b')
  def getHeights: List[Int] = List(0,2,2,2)
  def cellsToString(): String = ""
  def getColorsWithHeight0: List[Char] = List('b')
  def rows: Int = 2
  def cols: Int = 2
  def resetHeights: IGrid = this
  def toXML: Elem = <el el=""></el>

} 
开发者ID:GrimmT,项目名称:de.htwg.se.SevenSteps,代码行数:23,代码来源:GridMock.scala


示例7: XMLRequestSpec

//设置package包名称以及导入依赖的类
package play.api.libs.ws.ahc

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.util.ByteString
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.specification.AfterAll
import play.api.libs.ws.{ XML, XMLBodyReadables, XMLBodyWritables }
import play.shaded.ahc.org.asynchttpclient.{ Response => AHCResponse }

import scala.xml.Elem


class XMLRequestSpec extends Specification with Mockito with AfterAll {
  sequential

  implicit val system = ActorSystem()
  implicit val materializer = ActorMaterializer()

  override def afterAll: Unit = {
    system.terminate()
  }

  "write an XML node" in {
    import XMLBodyWritables._

    val xml = XML.parser.loadString("<hello><test></test></hello>")
    val client = mock[StandaloneAhcWSClient]
    val req = new StandaloneAhcWSRequest(client, "http://playframework.com/", null)
      .withBody(xml)
      .asInstanceOf[StandaloneAhcWSRequest]
      .buildRequest()

    req.getHeaders.get("Content-Type") must be_==("text/xml")
    ByteString.fromArray(req.getByteData).utf8String must be_==("<hello><test/></hello>")
  }

  "read an XML node" in {
    import XMLBodyReadables._

    val ahcResponse = mock[AHCResponse]
    ahcResponse.getResponseBody returns "<hello><test></test></hello>"
    val response = new StandaloneAhcWSResponse(ahcResponse)

    val expected = XML.parser.loadString("<hello><test></test></hello>")
    val actual = response.body[Elem]
    actual must be_==(expected)
  }
} 
开发者ID:playframework,项目名称:play-ws,代码行数:51,代码来源:XMLRequestSpec.scala


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


示例9: MovieMetaDataRecord

//设置package包名称以及导入依赖的类
package com.pacbio.secondary.analysis.legacy

import scala.collection.JavaConversions._
import java.net.URL
import java.io.File
import scala.xml.Elem



case class MovieMetaDataRecord(
    cellId: String,
    nCells: Int,
    pooledSampleName: String,
    sampleName: String,
    plateName: String,
    instrumentId: String,
    instrumentName: String,
    runId: String,
    runName: String,
    collectionProtocol: String,
    primaryVersion: String,
    primaryProtocol: String,
    collectionPath: String,
    primaryResultsFolder: String)

object MovieMetaDataXml {

  def loadFromElement(root: Elem): MovieMetaDataRecord = {
    // These are necessary to compute the required values
    val barcode = (root \ "EightPac" \ "Barcode").text
    val cellIndex = (root \ "CellIndex").text

    val cellId = barcode + '.' + cellIndex
    val nCells = 1234
    val pooledSampleName = "pooledSampleName"
    val sampleName = (root \ "Sample" \ "Name").text
    // Is this correct?
    val plateName = (root \ "Sample" \ "PlateId").text
    val instrumentId = (root \ "InstrumentId").text
    val instrumentName = (root \ "InstrumentName").text
    val runId = (root \ "Run" \ "Id").text
    val runName = (root \ "Run" \ "Name").text
    val collectionProtocol = (root \ "CollectionProtocol").text
    // Is this the primary version
    val primaryVersion = (root \ "version").text
    val primaryProtocol = (root \ "Primary" \ "Protocol").text

    // These aren't used in Aaron's model
    val instControlVersion = (root \ "InstCtrlVer").text
    val collectionPathUri = (root \ "Primary" \ "CollectionPathUri").text
    val primaryResultsFolder = (root \ "Primary" \ "ResultsFolder").text

    MovieMetaDataRecord(cellId, nCells, pooledSampleName, sampleName, instrumentId, instrumentId, runId, runName,
      collectionProtocol, primaryVersion, primaryProtocol, collectionPathUri, primaryResultsFolder, instControlVersion)
  }

  def loadFromFile(path: File): MovieMetaDataRecord = loadFromElement(scala.xml.XML.loadFile(path))
  def loadFromUrl(url: URL): MovieMetaDataRecord = loadFromElement(scala.xml.XML.load(url))


} 
开发者ID:PacificBiosciences,项目名称:smrtflow,代码行数:62,代码来源:MovieMetaDataXml.scala


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


示例11: PostFormTemplate

//设置package包名称以及导入依赖的类
package co.informatica.mvc.views

import scala.xml.Elem

object PostFormTemplate extends BaseTemplate {

  override def title: String = "Blog MVC | Iniciar Sesión"

  override def header: Elem =
    <header class="intro-header"></header>

  override def template(currentUser: String = ""): Elem =
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        <h3 class="text-center">Crear Nuevo Post</h3>
        <form action="/posts" method="post" novalidate="novalidate">
          <div class="row control-group">
            <div class="form-group col-xs-12 floating-label-form-group controls">
              <label for="title">Titulo</label>
              <input type="text" class="form-control" placeholder="Titulo" id="title" name="title" required="required" data-validation-required-message="Escribe el titulo del post."/>
              <p class="help-block text-danger"></p>
            </div>
          </div>
          <div class="row control-group">
            <div class="form-group col-xs-12 floating-label-form-group controls">
              <label for="subtitle">Subtitulo</label>
              <input type="text" class="form-control" placeholder="Subtitulo" id="subtitle" name="subtitle"/>
              <p class="help-block text-danger"></p>
            </div>
          </div>
          <div class="row control-group">
            <div class="form-group col-xs-12 floating-label-form-group controls">
              <label for="content">Contenido</label>
              <textarea class="form-control" placeholder="Contenido" id="content" name="content" required="required" data-validation-required-message="Escribe el cuerpo del post."></textarea>
              <p class="help-block text-danger"></p>
            </div>
          </div>
          <br/>
          <div class="row">
            <div class="form-group col-xs-12">
              <button type="submit" class="btn btn-default">Enviar</button>
            </div>
          </div>
        </form>
      </div>
    </div>
} 
开发者ID:jkevingutierrez,项目名称:MVC,代码行数:48,代码来源:PostFormTemplate.scala


示例12: LoginFormTemplate

//设置package包名称以及导入依赖的类
package co.informatica.mvc.views

import scala.xml.Elem

object LoginFormTemplate extends BaseTemplate {

  override def title: String = "Blog MVC | Iniciar Sesión"

  override def header: Elem =
    <header class="intro-header"></header>

  override def template(currentUser: String = ""): Elem =
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        <h3 class="text-center">Ingresa tus datos para iniciar sesion</h3>
        <form action="/login" method="post" novalidate="novalidate">
          <div class="row control-group">
            <div class="form-group col-xs-12 floating-label-form-group controls">
              <label for="name">Nombre</label>
              <input type="text" class="form-control" placeholder="Nombre" id="name" name="name" required="required" data-validation-required-message="Escribe tu nombre."/>
              <p class="help-block text-danger"></p>
            </div>
          </div>
          <div class="row control-group">
            <div class="form-group col-xs-12 floating-label-form-group controls">
              <label for="email">Correo electronico</label>
              <input type="email" class="form-control" placeholder="Correo electronico" id="email" name="email" required="required" data-validation-required-message="Escribe tu correo."/>
              <p class="help-block text-danger"></p>
            </div>
          </div>
          <br/>
          <div class="row">
            <div class="form-group col-xs-12">
              <button type="submit" class="btn btn-default">Enviar</button>
            </div>
          </div>
        </form>
      </div>
    </div>
} 
开发者ID:jkevingutierrez,项目名称:MVC,代码行数:41,代码来源:LoginFormTemplate.scala


示例13: UserFormTemplate

//设置package包名称以及导入依赖的类
package co.informatica.mvc.views

import scala.xml.Elem

object UserFormTemplate extends BaseTemplate {

  override def title: String = "Blog MVC | Iniciar Sesión"

  override def header: Elem =
    <header class="intro-header"></header>

  override def template(currentUser: String = ""): Elem =
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        <h3 class="text-center">Crear Nuevo Usuario</h3>
        <form action="/users" method="post" novalidate="novalidate">
          <div class="row control-group">
            <div class="form-group col-xs-12 floating-label-form-group controls">
              <label for="name">Nombre</label>
              <input type="text" class="form-control" placeholder="Nombre" id="name" name="name" required="required" data-validation-required-message="Escribe tu nombre."/>
              <p class="help-block text-danger"></p>
            </div>
          </div>
          <div class="row control-group">
            <div class="form-group col-xs-12 floating-label-form-group controls">
              <label for="email">Correo electronico</label>
              <input type="email" class="form-control" placeholder="Correo electronico" id="email" name="email" required="required" data-validation-required-message="Escribe tu correo."/>
              <p class="help-block text-danger"></p>
            </div>
          </div>
          <br/>
          <div class="row">
            <div class="form-group col-xs-12">
              <button type="submit" class="btn btn-default">Enviar</button>
            </div>
          </div>
        </form>
      </div>
    </div>
} 
开发者ID:jkevingutierrez,项目名称:MVC,代码行数:41,代码来源:UserFormTemplate.scala


示例14: RegisterFormTemplate

//设置package包名称以及导入依赖的类
package co.informatica.mvc.views

import scala.xml.Elem

object RegisterFormTemplate extends BaseTemplate {

  override def title: String = "Blog MVC | Registrar"

  override def header: Elem =
    <header class="intro-header"></header>

  override def template(currentUser: String = ""): Elem =
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        <h3 class="text-center">Ingresa tus datos para registrarte</h3>
        <form action="/register" method="post" novalidate="novalidate">
          <div class="row control-group">
            <div class="form-group col-xs-12 floating-label-form-group controls">
              <label for="name">Nombre</label>
              <input type="text" class="form-control" placeholder="Nombre" id="name" name="name" required="required" data-validation-required-message="Escribe tu nombre."/>
              <p class="help-block text-danger"></p>
            </div>
          </div>
          <div class="row control-group">
            <div class="form-group col-xs-12 floating-label-form-group controls">
              <label for="email">Correo electronico</label>
              <input type="email" class="form-control" placeholder="Correo electronico" id="email" name="email" required="required" data-validation-required-message="Escribe tu correo."/>
              <p class="help-block text-danger"></p>
            </div>
          </div>
          <br/>
          <div class="row">
            <div class="form-group col-xs-12">
              <button type="submit" class="btn btn-default">Enviar</button>
            </div>
          </div>
        </form>
      </div>
    </div>
} 
开发者ID:jkevingutierrez,项目名称:MVC,代码行数:41,代码来源:RegisterFormTemplate.scala


示例15: IndexTemplate

//设置package包名称以及导入依赖的类
package co.informatica.mvc.views

import co.informatica.mvc.models.Post

import scala.xml.Elem

object IndexTemplate extends BaseTemplate {

  var entities: Option[Iterator[Post]] = None

  override def template(currentUser: String = ""): Elem =
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        {entities match {
        case Some(entities) => {
          for (model <- entities) yield {
            <div class="post-preview">
              <a href={"/post/" + model.id}>
                <h2 class="post-title">
                  {model.title}
                </h2>
                <h3 class="post-subtitle">
                  {model.subtitle}
                </h3>
              </a>
              <p class="post-meta">Creado por
                {model.user.name}
                el día
                {model.createdDate}
              </p>
            </div>
                <hr/>
          }
        }
        case None => {
          <h3>No existe ningun post.</h3>
        }
      }}
      </div>
    </div>
} 
开发者ID:jkevingutierrez,项目名称:MVC,代码行数:42,代码来源:IndexTemplate.scala


示例16: SourceJson

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

import scala.xml.Elem
import org.json4s._
import org.json4s.native.JsonMethods._
case class SourceJson(value: String)

case class Order(orderNumber: String, customerName: String, itemPurchased: String)

object OrderXmlMapper {

  def mapOrder(order: Order): Elem = {
    <OrderHeader>
      <Body OrderNumber={order.orderNumber}
            Name={order.customerName}
            Item={order.itemPurchased}/>
    </OrderHeader>

  }
}

object JsonParser {
  implicit val formats = org.json4s.DefaultFormats
  def parseJson(json : String):Order={
    val v = parse(json).extract[Order]
    v
  }
} 
开发者ID:demojag,项目名称:AkkaStreamPoc,代码行数:29,代码来源:SourceJson.scala


示例17: ExerciseNine

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

import scala.xml.transform.{ RuleTransformer, RewriteRule }
import scala.xml.{ Attribute, Elem, Node, Null }

object ExerciseNine {

  def setDefaultImgAlt(input: Node, value: String): Seq[Node] = {
    val rule = new RewriteRule {
      override def transform(n: Node) = n match {
        case img @ <img /> if img \ "@alt" isEmpty => img.asInstanceOf[Elem] % Attribute(null, "alt", value, Null)
        case _ => n
      }
    }

    new RuleTransformer(rule).transform(input)
  }

} 
开发者ID:deekim,项目名称:impatient-scala,代码行数:20,代码来源:ExerciseNine.scala


示例18: ExerciseEight

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

import scala.collection.mutable.Map
import scala.xml.{ Elem, Text }

object ExerciseEight {

  def dlToMap(dl: Elem): Map[String, String] = {
    val map = Map[String, String]()

    val children = dl.child
    require(children.size % 2 == 0)
    for (i <- children.indices by 2) {
      (children(i), children(i + 1)) match {
        case (<dt>{Text(key)}</dt>, <dd>{Text(value)}</dd>) => map(key) = value
        case _ => ; // throw exception?
      }
    }

    map
  }

} 
开发者ID:deekim,项目名称:impatient-scala,代码行数:24,代码来源:ExerciseEight.scala


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


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



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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