문제

I have a question regarding list of elements in xml

I am trying to delete everything under and also the tags.

But when I debug my list of param I noticed my list looks like this :

text
element
text 
element
text
element
text 
element

But I want only the elements in the list and not the text so I can more easily delete the correct element. How to do this?

This is my code :

public void deleteParameter(int row, int index) {

        int objTypeIndex = index + 1;

        File xml = new File(XMLEditorService.getXMLEditorService().getFile());

        try {
            XMLOutputter xmlOut = new XMLOutputter();
            org.jdom2.Document doc = new SAXBuilder().build(xml);
            Namespace ns = Namespace.getNamespace("http://www.xxx.com");
            org.jdom2.Element rootNode = doc.getRootElement();
            org.jdom2.Element typeContent = rootNode.getChildren().get(
                    objTypeIndex);

            List<Element> list = typeContent.getChildren("param", ns);

            if (list.size() > 0) {
                Element element = list.get(row);   //remove correct element
                element.removeContent();

                System.out.println("element removed: " + element.getName());
                xmlOut.setFormat(Format.getPrettyFormat());
                xmlOut.output(doc, new FileWriter(XMLEditorService
                        .getXMLEditorService().getFile()));

            }

        } catch (IOException io) {
            System.out.println(io.getMessage());
        } catch (JDOMException jdomex) {
            System.out.println(jdomex.getMessage());
        }

    }

The list i am refering to is this line : List<Element> list = typeContent.getChildren("param", ns);

debug

도움이 되었습니까?

해결책

The method call: element.removeContent(); does not remove the Element from its parent, but instead it removes all content from the element (makes it empty).

You probably just want to do: element.detach(); instead.... which will remove the Element (and as a result all of its content too) from the document.

다른 팁

You could use a JDOM2 filter to get elements of a specific type. Look at This example to see how to retrieve specific elements of the XML using Filters in JDOM2.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top