2010-09-07 78 views
10

如何使用命名空间访问属性?我的XML数据的形式使用命名空间访问XML属性

val d = <z:Attachment rdf:about="#item_1"></z:Attachment> 

但下面如果我从属性的名称中删除命名空间的组件,然后它工作没有属性

(d \\ "Attachment" \ "@about").toString 

匹配。

val d = <z:Attachment about="#item_1"></z:Attachment> 
(d \\ "Attachment" \ "@about").toString 

任何想法如何使用Scala中的命名空间访问属性?

回答

12

API文档参考以下语法ns \ "@{uri}foo"

在你的例子中没有定义名称空间,看起来Scala认为你的属性是前缀。请参阅d.attributes.getClass

现在,如果你这样做:

val d = <z:Attachment xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" rdf:about="#item_1"></z:Attachment> 

然后:

scala> d \ "@{http://www.w3.org/1999/02/22-rdf-syntax-ns#}about" 
res21: scala.xml.NodeSeq = #item_1 

scala> d.attributes.getClass 
res22: java.lang.Class[_] = class scala.xml.PrefixedAttribute 
8

你总是可以做

d match { 
    case xml.Elem(prefix, label, attributes, scope, [email protected]_*) => 
} 

或在您的情况下,也匹配xml.Attribute

d match { 
    case xml.Elem(_, "Attachment", xml.Attribute("about", v, _), _, _*) => v 
} 

// Seq[scala.xml.Node] = #item_1 

然而,Attribute不关心前缀可言,所以如果你需要,你需要明确使用PrefixedAttribute

d match { 
    case xml.Elem(_, "Attachment", xml.PrefixedAttribute("rdf", "about", v, _), _, _*) => v 
} 

但是,如果存在多个属性,则存在问题。任何人都知道如何解决此问题?