All Downloads are FREE. Search and download functionalities are using the official Maven repository.

scales.xml.impl.XmlUtils.scala Maven / Gradle / Ivy

The newest version!
package scales.xml.impl

import scales.utils.collection.SeqLikeThing.immutableArrayProxyLikeThing
import scales.xml.{AttributeQName, Doc, ItemOrElem, Namespace, ScalesXml, Text, XCC, Xml10, XmlChildren, XmlItem, XmlTree, XmlVersion, convertFromScalaXml, defaultPathOptimisation, emptyChildren, loadXmlReader, xmlSeqLikeThing}
import scales.utils.resources.Loaner
import scales.xml.parser.strategies.{OptimisationToken, PathOptimisationStrategy}
import scales.xml.parser.sax.SaxSupport

/**
 * A collection of whitespace related functions
 */
trait Whitespace {
  import scales.utils.collection.Tree

  /**
   * XPath normalize-space function, replaces all consecutive whitespace with " " and trims.
   */
  def normalizeSpaceS(str: String) = str.replaceAll("\\s{2,}", " ").trim

  /**
   * Joins adjacent text nodes for immediate children
   */
  val mergeAdjacentText
    : ((Option[XmlItem], XmlChildren), ItemOrElem) => (Option[XmlItem], XmlChildren)
    = (pair: (Option[XmlItem], XmlChildren), item: ItemOrElem) =>
    if (item.isLeft && item.left.get.isInstanceOf[Text])
      // its an item
      // do we have a current text node?
      if (pair._1.isDefined) {
        val text = Text(pair._1.get.value + item.left.get.value)

        // replace the last
        (Some(text), xmlSeqLikeThing.:+(xmlSeqLikeThing.dropRight(pair._2)(1))(text))//Left(
      } else (Some(item.left.get), xmlSeqLikeThing.:+(pair._2)(item) : XmlChildren)
    else
      (None, xmlSeqLikeThing.:+(pair._2)(item) : XmlChildren)
  
  /**
   * Joins adjacent text nodes for the immediate children only (make a tree more XPath friendly) 
   */
  def joinTextNodes(tree: XmlTree) : XmlTree =
    Tree(tree.section, joinTextNodes(tree.children))

  def joinTextNodes(children : XmlChildren) : XmlChildren =
    children.foldLeft((None: Option[XmlItem], emptyChildren ))(mergeAdjacentText)._2


}

import org.xml.sax.XMLReader

trait XmlUtils {
  
  /**
   * Conversion from Scala XML into Scales XML
   */ 
  def convertFromScalaXml[Token <: OptimisationToken]( elem : scala.xml.Elem, parsers : Loaner[XMLReader] with SaxSupport = DefaultXMLReaderFactoryPool, optimisationStrategy : PathOptimisationStrategy[Token] = defaultPathOptimisation, encoding : String = "UTF-8" )(implicit xmlVer : XmlVersion)  : Doc = {
    // simple stream conversion.., for "large docs" a conversion in place might be better, but for now its isolated....
    var out = new java.io.StringWriter()
    val p = parsers						 
    scala.xml.XML.write(out, elem, encoding, true, null)
    import ScalesXml.readerToSource
    loadXmlReader[Token](new java.io.StringReader(out.toString), parsers = p, strategy = optimisationStrategy)
  }

  /**
   * Returns true if the tree is effectively empty, i.e. no attributes or children
   */
  def isEmptyTree(tree: XmlTree): Boolean = 
    (tree.children.isEmpty && tree.section.attributes.isEmpty)

  /**
   * A convenient AttributeQName for xsi:nil attributes
   */ 
  val xsiNil : AttributeQName = Namespace.xsi.prefixed("xsi", "nil")(Xml10, IsFromParser)

  /**
   * Tests if a given tree is nil, but does not check if children are present.
   *
   * @return true if there is a xsi:nil="true" value (or 1)
   */ 
  def isNil(tree: XmlTree): Boolean = {
    import ScalesXml._
    tree.section.attributes(xsiNil).
      map{b => java.lang.Boolean.parseBoolean(b.value) || (b.value == "1")}.getOrElse(false)
  }
    
}

trait XmlUtilsImplicits {
  class ToScales( elem : scala.xml.Elem)(implicit xmlVer : XmlVersion) {
    def asScales[Token <: OptimisationToken](parsers : Loaner[XMLReader] with SaxSupport = DefaultXMLReaderFactoryPool, optimisationStrategy : PathOptimisationStrategy[Token] = defaultPathOptimisation, encoding : String = "UTF-8" ) = convertFromScalaXml(elem, parsers, optimisationStrategy, encoding)
  }

  implicit def toScalesXml( elem : scala.xml.Elem)(implicit xmlVer : XmlVersion) = new ToScales(elem)
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy