在 Scala 中使用动态标签和属性构造 XML? [英] Construct XML with dynamic label and attributes in Scala?

查看:27
本文介绍了在 Scala 中使用动态标签和属性构造 XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够做到这一点:

I want to be able to do this:

val myXml = <myTag { someAttributes }> </myTag>

(因为编译时不知道属性细节是什么)

(because I don't know what the attribute details are at compile time)

还有这个:

val myXml = <{someTag}></{someTag}>

这不是有效的 Scala 语法.我最接近的是使用 Elem 对象来构造元素,但它有点麻烦(在我不想要的地方插入 PCDATA).有没有办法像上面那样做?

This isn't valid Scala syntax. The closest I can come is using the Elem object to construct elements, but it's being a little troublesome (inserting PCDATA where I don't want it to). Is there any way of doing it like the above?

推荐答案

val myXml = <myTag/> % Attribute(None, "name", Text("value"), Null)

请参阅 scala.xml.Attribute 以了解不同的构造函数.

See scala.xml.Attribute for different constructors.

为所有子级添加相同的属性:

Adding the same attribute to all children:

scala> val xml = <root><a/><b/><c/></root>
xml: scala.xml.Elem = <root><a></a><b></b><c></c></root>

scala> xml.child map (_ match {
     | case elem : Elem => elem % Attribute(None, "name", Text("value"), Null)
     | case x => x
     | })
res3: Sequence[scala.xml.Node] = ArrayBuffer(<a name="value"></a>, <b name="value"></b>, <c name="value"></c>)

您还可以使用 scala.xml.transform 中的内容递归地对所有 XML 执行此操作:

You can also use the stuff in scala.xml.transform to do so recursively to all XML:

val rr = new RewriteRule {
  override def transform(n: Node): Seq[Node] = n match {
    case elem : Elem => elem % Attribute(None, "name", Text("value"), Null) toSeq
    case other => other
  }
}

val rt = new RuleTransformer(rr)

scala> rt(xml)
res5: scala.xml.Node = <root name="value"><a name="value"></a><b name="value"></b><c name="value"></c></root>

或者你可以给xml的任意部分添加属性:

Or you can add attributes to arbitrary parts of the xml:

scala> val xml = <root>{<a/> % Attribute(None, "name", Text("value"), Null)}</root>
xml: scala.xml.Elem = <root><a name="value"></a></root>

编辑

在 Scala 2.8 上更改名称很容易,如下所示:

Changing the name is easy to do on Scala 2.8, like this:

val someTag = "tag"
val myXml = <root>{<a/>.copy(label = someTag)}</root>

这篇关于在 Scala 中使用动态标签和属性构造 XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆