我正在尝试使用 XmlSlurper 解析 XML 文档。这个文档有很多嵌套元素,每个元素都有一个值。它遵循以下格式:
<XML version="1" title="cars" lot="23">
<Cars>
<Car year="2012" color="black" engine="2.0L" drivetrain="FWD">Hyundai Sonata<Condition id="5">Excellent<Running>Yes</Running></Condition></Car>
<Car year="2007" color="silver" engine="2.4L" drivetrain="AWD">Audi A4<Condition id="4">Good<Running>Sometimes</Running></Condition></Car>
<Car year="2009" color="gray" engine="2.0L" drivetrain="FWD">Mitsubishi Lancer<Condition id="3">Fair<Running>Yes</Running></Condition></Car>
<Car year="1996" color="green" engine="5.0L" drivetrain="4WD">Jeep Grand Cherokee<Condition id="3">Fair<Running>No</Running></Condition></Car>
</Cars>
我正在尝试打印每辆车的年份和品牌/型号,但是,当我运行我的代码时,它会打印品牌/型号以及 Condition 和 Running 的值,如下所示:
id: 2012
value: Hyundai SonataExcellentYes
id: 2007
value: Audi A4GoodSometimes
id: 2009
value: Mitsubishi LancerFairYes
id: 1996
value: Jeep Grand CherokeeFairNo
我想知道如何隔离这些值中的每一个。这是我的代码:
class ParseCars {
static void main(String[] args) {
def carsXml = new XmlSlurper().parse("xml/cars.xml")
carsXml.Cars.Car.each{
def car = new Car()
car.year = it.@year.text() as Integer
car.makeModel = it
println "id: ${car.year}"
println "value: ${car.makeModel}"
println " "
}
}
}
我似乎找不到任何有关处理嵌套值的文档,其中父标签也包含这样的值。任何帮助将不胜感激。