关于查找具有与特定值匹配的属性的所有节点

关于查找具有与特定值匹配的属性的所有节点

本文介绍了关于查找具有与特定值匹配的属性的所有节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前在这里看到过以下示例,其中的目标是返回所有节点,这些节点包含一个 id 为 X 且包含值 Y 的属性:

//查找属性为class"且值为test"的所有节点val xml = XML.loadString("""

<span class="test">你好</span><div class="test"><p>hello</p></div></div>""" )def attributeEquals(name: String, value: String)(node: Node) ={node.attribute(name).filter(_==value).isDefined}val testResults = (xml \\ "_").filter(attributeEquals("class","test"))//打印:ArrayBuffer(//<span class="test">你好</span>,//<div class="test"><p>hello</p></div>//)println("测试结果:" + 测试结果)

我使用的是 Scala 2.7,每次返回的打印值始终为空.任何人都可以帮忙吗?抱歉,如果我正在复制另一个线程...但我认为如果我发布一个新线程会更明显吗?

解决方案

根据 Node ScalaDocattribute定义如下:

 def 属性(key: String):Option[Seq[Node]]

因此,您应该这样修改您的代码:

def attributeEquals(name: String, value: String)(node: Node) ={node.attribute(name).filter(_.text==value).isDefined//*text* 返回节点的文本表示}

但为什么不实现同样的简单:

scala>(xml 后代或自我)过滤器{节点 =>(node \ "@class").text == "test"}res1: List[scala.xml.Node] = List(<span class="test">hello</span>, <div class="test"><p>hello</p></div>)

I saw the following example disccussed here previously, where the goal was to return all nodes that contain an attribute with an id of X that contains a value Y:

    //find all nodes with an attribute "class" that contains the value "test"
val xml = XML.loadString( """<div>
<span class="test">hello</span>
<div class="test"><p>hello</p></div>
</div>""" )

def attributeEquals(name: String, value: String)(node: Node) =
{
    node.attribute(name).filter(_==value).isDefined
}

val testResults = (xml \\ "_").filter(attributeEquals("class","test"))
//prints: ArrayBuffer(
//<span class="test">hello</span>,
//<div class="test"><p>hello</p></div>
//)
println("testResults: " + testResults)

I am using Scala 2.7 and everytime the return printed value is always empty. Anyone could help on that ?Sorry if I am copying another thread... but thought it would be more visible if I posted a new one ?

解决方案

According to Node ScalaDoc, attribute is defined as follows:

 def attribute(key: String):Option[Seq[Node]]

Therefore, you should modify your code that way:

def attributeEquals(name: String, value: String)(node: Node) =
{
    node.attribute(name).filter(_.text==value).isDefined // *text* returns a text representation of the node
}

But why not just achieving the same simpler:

scala> (xml descendant_or_self) filter{node => (node \ "@class").text == "test"}
res1: List[scala.xml.Node] = List(<span class="test">hello</span>, <div class="test"><p>hello</p></div>)

这篇关于关于查找具有与特定值匹配的属性的所有节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 23:21