13

What's the simplest API to use in scala to perform the following XPath queries on a document?

//s:Annotation[@type='attitude']/s:Content/s:Parameter[@role='type' and not(text())]

//s:Annotation[s:Content/s:Parameter[@role='id' and not(text())]]/@type

(s is defined as a nickname for a particular namespace)

The only documentation I can find on Scala's XML libraries has no information on performing complicated real XPath queries.

I used to like JDOM for this purpose (in Java), but since JDOM doesn't support generics, it will be painful to work with in Scala. (Other XML libraries for Java have tended to be even more painful in Java, but I admit I don't know the landscape real well.)

4

5 に答える 5

12
//s:Annotation[@type='attitude']/s:Content/s:Parameter[@role='type' and not(text())]

Well, I don't understand the s: notation, and couldn't find it on XPath spec either. However, ignoring that this would look like this:

(
  (xml 
    \\ "Annotation" 
    filter (_ \ "@type" contains Text("x"))
  ) 
  \ "Content" 
  \ "Parameter" 
  filter (el => (el \ "@type" contains Text("type")) && el.isInstanceOf[Text])
)

Note the necessity of parenthesis because of higher precedence of \ over filter. I have changed the formatting to a multi-line expression as the Scala equivalent is just way too verbose for a single line.

I can't answer about namespaces, though. No clue how to work with them on searches, if it's even possible. The docs mention @{uri}attribute for prefixed attributes, not does not mention anything about prefixed elements. Also, note that you need to pass an uri which resolves to the namespace you want, as literal namespaces in search are not supported.

于 2010-06-16T22:14:52.117 に答える
3

軽くポン引きするXOMで行くと思います。XOMの作成者が子ノードなどのコレクションを公開しないことを決定したのは少し残念ですが、JavaではScalaよりも多くの作業と利点がありませんでした。(そして、それは他の点ではうまく設計されたライブラリです。)

編集: XOMはXPathクエリを事前にコンパイルしないため、結局JDOMをポン引きすることになりました。今回はほとんどの努力がXPathに向けられていたので、ジェネリックの問題のほとんどを回避する優れたモデルを思いつくことができました。getChildrenメソッドの妥当な汎用バージョンを思い付くのはそれほど難しいことではありませんgetAttributes(名前が少し変更getAdditionalNamespacesorg.jdom.Elementれた新しいメソッドでライブラリをポン引きすることによって)。の修正はないと思いますがgetContent、私はそうではありません確かにgetDescendants

于 2010-06-17T14:23:57.790 に答える
3

Scales Xml adds both string based full XPath evaluation and an internal DSL providing a fairly complete coverage for querying

于 2011-11-04T22:31:32.163 に答える
1

scalaxmljaxenが成熟すると、scalaの組み込みXMLクラスでこれを確実に実行できるようになると思います

于 2010-06-21T02:40:35.463 に答える
0

I would suggest using kantan.xpath:

 import kantan.xpath._
 import kantan.xpath.implicits._

 input.evalXPath[List[String]](xp"/annotation[@type='attitude']/content/parameter[@role='type' and not(text())]/@value")

This yields:

res1: kantan.xpath.XPathResult[List[String]] = Success(List(foobar))
于 2017-10-26T14:36:49.593 に答える