仅当节点具有特定值的特定属性时才提取节点

时间:2009-12-22 18:26:13

标签: xml scala parsing

在此this post的基础上,我需要一种简洁的方法来提取节点中的节点,只有它们具有特定的属性值。这就是我想出的:

def attributeValue(attrs: (String, String)*)(n: Node) = 
  attrs.map { p =>
    n.attribute(p._1).exists(_ == p._2)
  } reduceLeft(_ && _)

这是一个使用它从原子提取中提取项目对象的例子。

def parseAtomItems(ns: NodeSeq) = ns \\ "entry" flatMap { i =>
  for(
    t <- i \ "title";
    l <- i.\("link").filter(attributeValue(
        "type"  -> "text/html",
        "rel"   -> "alternate"
        ).flatMap(_.attribute("href"))
    ) yield FeedItem(t text, l text)
}

我的问题是:是否有更清洁/更惯用的方式来实现attributeValue?

1 个答案:

答案 0 :(得分:2)

我认为代码实际上相当不错。我这样做:

def attributeValue(attrs: (String, String)*)(n: Node) =   
  attrs forall { 
    case (key, value) => n attribute key exists (_ == value)
  }

可替换地,

def attributeValue(attrs: (String, String)*)(n: Node) =   
  attrs forall { 
    case (key, value) => n \ ("@"+key) exists (_ == value)
  }

forall超过reduceLeft的主要优点是前者将在第一个错误结果处停止,而后者将迭代每个键/值对,即使保证错误匹配也是如此。