cak*_*e3d 10 xml parsing scala
如何使用命名空间访问属性?我的XML数据是一种形式
val d = <z:Attachment rdf:about="#item_1"></z:Attachment>
Run Code Online (Sandbox Code Playgroud)
但以下内容与属性不匹配
(d \\ "Attachment" \ "@about").toString
Run Code Online (Sandbox Code Playgroud)
如果我从属性的名称中删除命名空间组件,那么它可以工作.
val d = <z:Attachment about="#item_1"></z:Attachment>
(d \\ "Attachment" \ "@about").toString
Run Code Online (Sandbox Code Playgroud)
知道如何在Scala中使用命名空间访问属性吗?
huy*_*hjl 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>
Run Code Online (Sandbox Code Playgroud)
然后:
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
Run Code Online (Sandbox Code Playgroud)
你总能这样做
d match {
case xml.Elem(prefix, label, attributes, scope, children@_*) =>
}
Run Code Online (Sandbox Code Playgroud)
或者在你的情况下也匹配 xml.Attribute
d match {
case xml.Elem(_, "Attachment", xml.Attribute("about", v, _), _, _*) => v
}
// Seq[scala.xml.Node] = #item_1
Run Code Online (Sandbox Code Playgroud)
但是,Attribute根本不关心前缀,因此如果您需要,则需要明确使用PrefixedAttribute:
d match {
case xml.Elem(_, "Attachment", xml.PrefixedAttribute("rdf", "about", v, _), _, _*) => v
}
Run Code Online (Sandbox Code Playgroud)
但是,当存在多个属性时会出现问题.谁知道如何解决这个问题?
| 归档时间: |
|
| 查看次数: |
2158 次 |
| 最近记录: |