我有以下XML:
<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做到这一点?我似乎遇到的问题是当我分离元素时,我似乎无法将其添加回我所拥有的列表中。
答案 0 :(得分:0)
我设法通过创建一个新列表然后使用新的迭代器迭代这个列表来实现这一点,如下面的代码所示:
// 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();
Iterator<Element> iterator2 = element.elementIterator();
while(iterator2.hasNext())
{
Element newCurrentElement = (Element)iterator2.next();
if(newCurrentElement.getName().equals("MaxSpeed"))
{
newCurrentElement.detach();
elementList.add(elementList.indexOf(currentElement), newCurrentElement);
}
}
}
}