【问题标题】:in regards of finding all nodes that have an attribute that matches a certain value with scala关于查找具有与 scala 的某个值匹配的属性的所有节点
【发布时间】:2015-02-11 06:40:39
【问题描述】:

我看到了前面讨论过的以下示例,其目标是返回所有包含 id 为 X 且包含值 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) 

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

【问题讨论】:

    标签: xml scala


    【解决方案1】:

    根据Node ScalaDocattribute定义如下:

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

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

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

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

    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>)
    

    【讨论】:

    • 非常感谢,这正是它所缺少的! :)
    猜你喜欢
    • 2013-10-26
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多