0
在XML相同水平的運動元素我有下面的XML:使用dom4j的
<Vehicle xmlns="http://www.cartest.co.uk">
<Car>
<EngineSize>2100</EngineSize>
<Color>Green</Color>
<NoOfDoors>5</NoOfDoors>
<MaxSpeed>150</MaxSpeed>
<Interior>Leather</Interior>
</Car>
<Car>
<EngineSize>1000</EngineSize>
<Color>Red</Color>
<NoOfDoors>3</NoOfDoors>
<MaxSpeed>120</MaxSpeed>
<Interior>Leather</Interior>
</Car>
<Car>
<EngineSize>1400</EngineSize>
<Color>Blue</Color>
<MaxSpeed>100</MaxSpeed>
<Interior>Fabric</Interior>
</Car>
</Vehicle>
我想要做的就是解析文檔,如果NoOfDoors元素存在,將它上面的MAXSPEED元素。
所以採取上述示例XML,我會得到下面的輸出:
<Vehicle xmlns="http://www.cartest.co.uk">
<Car>
<EngineSize>2100</EngineSize>
<Color>Green</Color>
<MaxSpeed>150</MaxSpeed>
<NoOfDoors>5</NoOfDoors>
<Interior>Leather</Interior>
</Car>
<Car>
<EngineSize>1000</EngineSize>
<Color>Red</Color>
<MaxSpeed>120</MaxSpeed>
<NoOfDoors>3</NoOfDoors>
<Interior>Leather</Interior>
</Car>
<Car>
<EngineSize>1400</EngineSize>
<Color>Blue</Color>
<MaxSpeed>100</MaxSpeed>
<Interior>Fabric</Interior>
</Car>
</Vehicle>
我已經創建了下面的代碼片段(很多其他的嘗試中),我只是不能似乎得到它的工作:
// Parse the XML document
doc = ParseDocument(fileName);
// Deal with default namespace
HashMap map = new HashMap();
map.put("ns", "http://www.cartest.co.uk");
Dom4jXPath xpath = new Dom4jXPath("//ns:Car");
xpath.setNamespaceContext(new SimpleNamespaceContext(map));
List<Node> nodes = xpath.selectNodes(doc);
for(Node node : nodes)
{
Element element = (Element)node;
Iterator<Element> iterator = element.elementIterator();
while(iterator.hasNext())
{
Element currentElement = (Element)iterator.next();
if(currentElement.getName().equals("NoOfDoors"))
{
List<Element> elementList = currentElement.getParent().elements();
for(Element elements : elementList)
{
if(elements.getName().equals("MaxSpeed"))
{
Node moveNode = elements.detach();
elementList.add(elementList.indexOf(elements), (Element) moveNode);
}
}
}
}
}
運行時提供了以下錯誤的代碼:
java.lang.IndexOutOfBoundsException: Index: -1
任意子í知道如何使用Dom4J做到這一點?我似乎遇到的問題是當我分離元素時,我似乎不能將它添加回到我擁有的列表中。