문제

Here's my XML file:

<?xml version="1.0" encoding="UTF-8"?>
<record>
  <data id="2-1">
    <ns>45</ns>
    <hfdi />
    <hfdv>0.26</hfdv>
  </data>
  <data id="2-3">
    <ns>49</ns>
    <hfdi />
    <hfdv>0.34</hfdv>
  </data>
</record>

I tried to remove the elements with specific attribute by using JDOM.

Document doc =null;
try{
    InputStream is = Files.newInputStream(Paths.get("config.xml"),StandardOpenOption.READ)
    doc = (Document)((new SAXBuilder()).build(is));
}catch(Exception ex){//do something}

for(Element elem : doc.getRootElement().getChildren("data")){
    if(elem.getAttribute("id").getValue().equals("2-3")){
        elem.detach();
    }
}

XMLOutputter xo = new XMLOutputter();
xo.setFormat(Format.getPrettyFormat());
try{
    OutputStream os = Files.newOutputStream(Paths.get("config.xml"), StandardOpenOption.WRITE)
    xo.output(doc, os);
}catch(Exception ex){//do something}

Then my XML become like this:

<?xml version="1.0" encoding="UTF-8"?>
<record>
  <data id="2-1">
    <ns>45</ns>
    <hfdi />
    <hfdv>0.26</hfdv>
  </data>
</record>
  "2-3">
    <ns>49</ns>
    <hfdi />
    <hfdv>0.34</hfdv>
  </data>
</record>

The element "2-3" is still there with no head!!!!

It seems that the element I want to delete does note be removed properly. How can I fix it?

Any help will be highly appreciated.

도움이 되었습니까?

해결책

Xing, I believe you must have a file open for writing, and then you overwrite the beginning of the file, but you don't truncate the file first. You end up with what you have there.

As for the detatch() vs. removeContent(...), the detatch will be faster, but is not what's causing your problem here.

Can you provide more detail on how you open and write to the file?

EDIT: excellent. Your Files.newOutputStream(....) method call needs to have the TRUNCATE_EXISTING option set as well as the WRITE OPTION.

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