0

我正在使用 javax xml 来解析 XML,我想要在所有子项中包含父项。

<a>
   <b value1 = "b1", value2 = "b2">
       <c value1 = "c1", value2 = "c2" />
       <c value1 = "c3", value2 = "c4" />
   </b>
   <b value1 = "b3">
       <c value1="c5" />
       <c value1 ="c6" />
   </b>
</a>

我希望结果的形式如下:

Set((b1,c1,c2), (b1,c3,c4), (b3, c5, ""), (b3, c6, "")) 
4

1 回答 1

2

以下是我如何在 Scala 中使用 XML 文字来实现这一点。这不是最有效的方法,但它实现了您指定的目标:

scala> val xml: scala.xml.Elem = <a>
  <b value1="b1" value2="b2">
    <c value1="c1" value2="c2"/>
    <c value1="c3" value2="c4"/>
  </b>
  <b value1="b3">
    <c value1="c5"/>
    <c value1="c6"/>
  </b>
</a>

scala> val bs = xml\ "b"
bs: scala.xml.NodeSeq = <b value1="b1" value2="b2">
    <c value1="c1" value2="c2"/>
    <c value1="c3" value2="c4"/>
  </b><b value1="b3">
    <c value1="c5"/>
    <c value1="c6"/>
  </b>

scala> val gatheringNodes = bs.map { b =>
  val cs = b\"c"
  b\"@value1" -> cs.map(c => (c\"@value1", c\"@value2"))
}
gatheringNodes: scala.collection.immutable.Seq[(scala.xml.NodeSeq, scala.collection.immutable.Seq[(scala.xml.NodeSeq, scala.xml.NodeSeq)])] = List((b1,List((c1,c2), (c3,c4))), (b3,List((c5,), (c6,))))

scala> val finalOutput = gatheringNodes.flatMap { case(b, cs) =>
    cs.map { case(c1, c2) => (b, c1, c2)}
}.toSet
finalOutput: scala.collection.immutable.Set[(scala.xml.NodeSeq, scala.xml.NodeSeq, scala.xml.NodeSeq)] = Set((b1,c1,c2), (b1,c3,c4), (b3,c5,), (b3,c6,))
于 2017-05-09T00:36:18.467 回答