gpt4 book ai didi

xml - Scala XML 序列化

转载 作者:数据小太阳 更新时间:2023-10-29 01:46:34 26 4
gpt4 key购买 nike

看到 Scala 的强大功能,我想知道是否可以使用内置的 Scala 语言功能和库(例如,没有 XMLEncoder、XStream 或 JAXB)将任意对象图序列化为 XML 或反序列化为 XML。不幸的是,我还没有找到这样的解决方案。你有什么建议?

最佳答案

我不知道“是否可以使用内置的 Scala 语言功能和库将任意对象图序列化和反序列化为 XML”,但由于 Scala 中有一些对 XML 的原生支持,我会提到他们。可以在 Ch. 中找到更多详细信息。 26 Programming in Scala称为使用 XML:

This chapter introduces Scala's support for XML. After discussing semi-structured data in general, it shows the essential functionality in Scala for manipulating XML: how to make nodes with XML literals, how to save and load XML to files, and how to take apart XML nodes using query methods and pattern matching.

为了快速总结本章,我将引用一些要点。

  • Scala 包括对处理 XML 的特殊支持。
  • Scala 允许您在表达式有效的任何地方以文字形式输入 XML。
  • 您可以使用花括号 ({}) 作为转义符,在 XML 文字的中间计算 Scala 代码。

所以你可以这样写:

val foo = <a> {3 + 4} </a>

上面的计算结果为 scala.xml.Elem = <a> 7 </a> .

  • 如果你想通过标签名查找子元素,只需调用\即可。标签名称。
  • 您可以使用 \\ 进行“深度搜索”并查看子元素等。而不是 \运算符(operator)。

书上有一个抽象类的序列化和反序列化的例子,不过是手写的:

abstract class CCTherm {
val description: String
val yearMade: Int

def toXML =
<cctherm>
<description>{description}</description>
<yearMade>{yearMade}</yearMade>
</cctherm>

def fromXML(node: scala.xml.Node): CCTherm =
new CCTherm {
val description = (node \ "description").text
val yearMade = (node \ "yearMade").text.toInt
}
}

还可以在名为 scala.xml 的草稿书中找到更多信息。 .

关于xml - Scala XML 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/756317/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com