2010-11-18 86 views
0

在Scala中,我如何改變:將XML轉換爲乳膠

<p>here we have a <a href="http://www.scala-lang.org/api/current/index.html">link</a> example.</p> 

here we have a \url{http://www.scala-lang.org/api/current/index.html}{link} example. 

其中<p></p>映射到 「無」,並<a href"_">_</>映射到\url{_}{_}

+1

'

'應該段落 – 2010-11-19 05:17:25

回答

-1

定義的正則表達式:

scala> val link = """<a href="(.+)">(.+)</a>""".r 
link: scala.util.matching.Regex = <a href="(.+)">(.+)</a> 

scala> val paragraph = """<p>(.+)</p>""".r 
paragraph: scala.util.matching.Regex = <p>(.+)</p> 

scala> val text = """<p>here we have a <a href="http://www.scala-lang.org/api/current/index.html">link</a> example.</p>""" 
text: java.lang.String = <p>here we have a <a href="http://www.scala-lang.org/api/current/index.html">link</a> example.</p> 

它們適用於輸入:

scala> val modifiedText = paragraph.replaceAllIn(text, {matched => val paragraph(content) = matched; content}) 
modifiedText: String = here we have a <a href="http://www.scala-lang.org/api/current/index.html">link</a> example. 

scala> link.replaceAllIn(modifiedText, {matched => val link(href, title) = matched; "\\\\url{%s}{%s}" format(href, title)}) 
res11: String = here we have a \url{http://www.scala-lang.org/api/current/index.html}{link} example. 
+0

結束後映射到一個空白行,現在two urls

嘗試在一個 Debilski 2010-11-18 12:49:07

+0

只需要一個更復雜的正則表達式,像'([^<>]*)'' – 2010-11-18 13:11:32

+0

'我會使用類似']*>\([^<]*)'的東西,這樣它就不會在'a'元素中存在其他屬性(比如'style'或'class'或者其他的東西)。 – 2010-11-18 17:43:40

3

作爲替代方案,如果你需要更多的轉換*,你可以用這個啓動。它也將與嵌套的<a/>標籤一起工作,無論這種標籤如何可能。

代碼中有一些需要轉義處理的地方。例如。一些字符以XML格式轉義,而這些字符在Latex中不會轉義,反之亦然。隨意添加此。

import xml._ 

val input = <p>And now try it on a <a href="link1">text</a> with <a href="link2">two urls</a></p> 

def mkURL(meta: MetaData, text: String) = { 
    val url = meta.asAttrMap.get("href") 
    "\\url{%s}{%s}".format(url getOrElse "", text) 
} 

def transform(xhtml: NodeSeq): String = { 
    xhtml.map { node => 
    node match { 
     case Node("p", _, [email protected]_*) => transform(ch) 
     case Node("a", meta, [email protected]_*) => mkURL(meta, transform(ch)) 
     case x => x.toString 
    } 
    } mkString 
} 

println(transform(input)) 

// And now try it on a \url{link1}{text} with \url{link2}{two urls} 

[*]增加對\emph支持會是這樣的

case Node("em", _, [email protected]_*) => transform(ch).mkString("\\emph{", "", "}") 
0

更通用的方法是使用的解析器,像Scala的解析器組合,或Java的可用的。 如果該文件格式良好的xml,處理xml的方式也可以。