0
val template = <root>
    <component>
        <mother-board>
            <manufacturer>
                <name>
                </name
            </manufacturer>
            <price>
                555
            </price>
            <chipset>
                Intel
            </chipset>
        </mother-board>
    </component>
</root>

val xPaths = Map("root/component/mother-board/manufacturer/name" -> "Asus")

val output = <root>
    <component>
        <mother-board>
            <manufacturer>
                <name>
                  Asus
                </name>
            </manufacturer>
            <price>
                555
            </price>
            <chipset>
                Intel
            </chipset>
        </mother-board>
    </component>
</root>

真正的模板超过 250 行,需要填充的 xpath 数量超过 70 个。欢迎任何关于库或任何其他可以实现这一点的方法的建议。谢谢你。

更新以添加有关我的方法的信息
到目前为止我所做的不起作用:我基于可用的 XPaths 创建 XML。但是如果 XPath 的处理顺序发生变化,XML 也会发生变化,这对我的用例来说是不可接受的。

object Main extends App {
  val props = Map(
    "a/b/c" -> "val1",
    "a/b/d/f" -> "val3",
    "a/b/d/e" -> "val2"
  )

  println(props.keys.foldLeft(<root/>: Node)((acc, current) => {
    create(Elem(acc.prefix, acc.label, acc.attributes, acc.scope, true, acc.child: _*), current.split("/").toList, current, props)
  }))

  def create(node: Elem, path: List[String], completePath: String, propMap: Map[String, String]): Node = {
    if(path.size > 0) {
      val current = path.head
      node.child.filter(x => x.label.equals(current)).headOption.map(childToTraverse => {
        val newChild = create(Elem(null, childToTraverse.label, childToTraverse.attributes, childToTraverse.scope, false, childToTraverse.child: _*), path.tail, completePath, propMap)
        node.copy(child = node.child.filter(x => !x.label.equals(current)) ++ newChild)
      }).getOrElse({
        val newNode = Elem(null, current, node.attributes, node.scope, false)
        val newChild = create(newNode, path.tail, completePath, propMap)
        node.copy(child = node.child ++ newChild)
      })
    }
    else {
      node.copy(child = new Text(propMap.get(completePath).getOrElse("Value Not Available")))
    }
  }
}

问题:

对于输入:

"a/b/c" -> "val1",
"a/b/d/f" -> "val3",
"a/b/d/e" -> "val2"

它生成:

<root>
    <a>
        <b>
            <c>
                val1
            </c>
            <d>
                <f>
                    val3
                </f>
                <e>
                    val2
                </e>
            </d>
        </b>
    </a>
</root>

对于输入:

"a/b/c" -> "val1",
"a/b/d/e" -> "val2",
"a/b/d/f" -> "val3"

它生成:

<root>
    <a>
        <b>
            <c>
                val1
            </c>
            <d>
                <e>
                    val2
                </e>
                <f>
                    val3
                </f>
            </d>
        </b>
    </a>
</root>

请注意从以不同顺序处理的相同 XPath 生成的两个 XML 的区别。
我知道正确的顺序。所以我想要有模板并基于 XPaths 更改模板,而不是从头开始生成 XML。

4

0 回答 0