使用重写规则的 Scala XML 转换

Scala XML transformation with Rewrite rules

我有一个 XML 模板,其中预定义了一些字段。我想使用 RewriteRules.

基于它的模板和新的 Value 值构建新的 XML

例如。 模板:

val template = <xml>
  <Persons>
    <Name>Persons</Name>
    <Person>
      <FullName>
        <Name>Name of the field</Name>
        <Value></Value>
      </FullName>
      <LastName>
        <Name>Name of the field</Name>
        <Value></Value>
      </LastName>
    </Person>
  </Persons>
</xml>

case class Person(fullName: String, lastName: String)
val persons = Seq(Person("John Smith", "Smith"), Person("Bob Saver", "Saver"))

输出应该是:

<xml>
  <Persons>
    <Name>Persons</Name>
    <Person>
      <FullName>
        <Name>Name of the field</Name>
        <Value>John Smith</Value>
      </FullName>
      <LastName>
        <Name>Name of the field</Name>
        <Value>Smith</Value>
      </LastName>
    </Person>
    <Person>
      <FullName>
        <Name>Name of the field</Name>
        <Value>Bob Saver</Value>
      </FullName>
      <LastName>
        <Name>Name of the field</Name>
        <Value>Saver</Value>
      </LastName>
    </Person>
  </Persons>
</xml>

可以用RewriteRules吗?

您不需要 RewriteRules 用于此目的。您可以在 xml 模板中定义变量。

scala> def template(id: String = "defaultValue can be here") = <someXml>{id}</someXml>
template: (id: String)scala.xml.Elem

scala> template("person")
res4: scala.xml.Elem = <someXml>person</someXml>
scala> template("person2")
res5: scala.xml.Elem = <someXml>person2</someXml>

否则 Scala - replace xml element with specific text