让我们举一个例子,假设您有这个 XML。
<?xml version="1.0" encoding="UTF-8"?>
<test>
<KeyEvents>
<num_events>4</num_events>
<event_1>
<distance>0.044</distance>
</event_1>
<event_2>
<distance>0.055</distance>
</event_2>
<event_3>
<distance>3.778</distance>
</event_3>
<event_4>
<distance>3.822</distance>
</event_4>
<Summary>
<total_distance>7.699</total_distance>
</Summary>
</KeyEvents>
</test>
问题是每个 XML 文件都会不同,并且具有不同数量的 event_[x]。所以本质上可能有 4 个、300 个甚至没有。
这就是模型。
@XmlRootElement(name = "test")
public class test {
private int numEvents;
private Event event;
private Summary summary;
public static class Event {
private double distance;
@XmlElement(name = "distance")
public double getDistance() {
return distance;
}
}
public static class Summary {
private double totalDistance;
@XmlElement(name = "total_distance")
public double getTotalDistance() {
return totalDistance;
}
}
}
最终目标是迭代所有“事件”并获取每个事件的每个距离,然后将它们打印到控制台(总会有一个摘要)。
我尝试过将事件存储为地图。示例:
private Map<String, Event> events;
但我似乎无法解压和迭代所有事件。有什么帮助吗?珍惜时间。
尝试 powershell 脚本
using assembly System.Xml.Linq
$filename = "c:\temp\test.xml"
$doc = [System.Xml.Linq.XDocument]::Load($filename)
$keyEvents = $doc.Descendants("KeyEvents")[0]
$events = [System.Linq.Enumerable]::Where($keyEvents.Elements(), [Func[object,bool]]{ param($x) $x[0].Name.LocalName.StartsWith('event')})
$table = [System.Collections.ArrayList]::new()
foreach($event in $events)
{
$newRow = [pscustomobject]@{
Name = $event.Name.LocalName
Distance = $Event.Element('distance').Value
}
$table.Add($newRow) | Out-Null
}
$summary = $keyEvents.Element('Summary').Value
$newRow = [pscustomobject]@{
Name = 'Summary'
Distance = $summary
}
$table.Add($newRow) | Out-Null
$table
结果
Name Distance
---- --------
event_1 0.044
event_2 0.055
event_3 3.778
event_4 3.822
Summary 7.699