2013-12-19 4 views
1

Это мой XML-файлКак удалить дочерний элемент из XML в java?

<?xml version="1.0" encoding ="utf-8" ?> 
<mcss> 
    <quest ans="1"> 
     <question><![CDATA[Write 5x= 3y-1 as linear equation form.]]></question> 
     <options> 
      <option><![CDATA[5x-3y+1=0]]></option> 
      <option><![CDATA[-5x-3y-1=0]]></option> 
      <option><![CDATA[5x+3y+1=0]]></option>   
     </options> 
     <explaination><![CDATA[Recall the linear equation in two variables form.]]></explaination> 
    </quest> 
</mcss> 

Я просто хочу, чтобы удалить 2-ой один вариант из моего XML.
Мой код Java удаляет всю опцию из моего элемента options. с помощью option.getParentElement().removeChild("option");

try { 
    String path="D://test//n2027_set1.xml"; 
    File structureXml = new File(path); 
    SAXBuilder saxb = new SAXBuilder(); 
    Document document = saxb.build(structureXml); 
    Element rootElement = document.getRootElement(); 
    XMLOutputter xmlOutput = new XMLOutputter(); 

    List qestList = rootElement.getChildren(); 
    for (int i = 0; i < qestList.size(); i++) { 
     Element quesList = (Element) qestList.get(i); 
     System.out.println(quesList.getAttributeValue("ans")); 
     //change ans field 
     quesList.setAttribute("ans", ""+i); 
     List qList = quesList.getChildren(); 
     for(int a=0;a< qList.size();a++) { 
      Element ques =(Element) qList.get(a); 
      if(ques.getAttributeValue("file")!=null){ 
       //read xml 
       System.out.println(ques.getAttributeValue("file")); 
       //write xml attribute 
       //System.out.println(ques.setAttribute("file","dasd"+a)); 
      } 
      if(ques.getName().equalsIgnoreCase("question")){ 
       //read 
       System.out.println(ques.getTextTrim()); 
       ques.addContent(new CDATA(ques.getTextTrim())); 
      } 
      if (ques.getName().equalsIgnoreCase("options")) { 
       List optList = ques.getChildren(); 
       for (int k = 0; k < optList.size(); k++) { 
        Element option = (Element) optList.get(k); 
        if(option.getName().equalsIgnoreCase("option")){ 
         //read 
         option.getParentElement().removeChild("option"); 
        } 
       } 
      } 
      if(ques.getName().equalsIgnoreCase("explaination")){ 
       ques.removeContent(); 
       ques.addContent(new CDATA("explaination"+a)); 
      } 
     } 
    }   
    FileOutputStream file=new FileOutputStream(path); 
    xmlOutput.output(document, file); 
}catch (JDOMException ex) { 
    ex.printStackTrace(); 
} catch (IOException ex) { 
    ex.printStackTrace(); 
} 

моего выхода является:

<?xml version="1.0" encoding ="utf-8" ?> 
<mcss> 
    <quest ans="1"> 
     <question><![CDATA[Write 5x= 3y-1 as linear equation form.]]></question> 
     <options> 

     </options> 
     <explaination><![CDATA[Recall the linear equation in two variables form.]]></explaination> 
    </quest> 
</mcss> 

, но я хочу, как это.

<?xml version="1.0" encoding ="utf-8" ?> 
<mcss> 
    <quest ans="1"> 
     <question><![CDATA[Write 5x= 3y-1 as linear equation form.]]></question> 
     <options> 
      <option><![CDATA[5x-3y+1=0]]></option> 
      <option><![CDATA[-5x-3y-1=0]]></option> 

     </options> 
     <explaination><![CDATA[Recall the linear equation in two variables form.]]></explaination> 
    </quest> 
</mcss> 

ответ

4

Element.removeChild удалит только первого ребенка с заданным именем. Вы можете использовать Element.removeContent(int index) удалить дочерний элемент по индексу

if (ques.getName().equalsIgnoreCase("options")) { 
    ques.removeContent(2); 
} 

или Element.removeContent(Content content) удалить определенный элемент.

if (ques.getName().equalsIgnoreCase("options")) { 
    List<Element> options = ques.getChildren("option"); 
    if(options.size()>2) { 
     Element optionToRemove = options.get(2); 
     ques.removeContent(optionToRemove); 
    } 
}  

Вы сказали, что хотите удалить второй вариант, но в вашем примере третий удаляется. Я немного смущен, поэтому при необходимости измените индекс.

+0

plz см. Этот вопрос..http: //stackoverflow.com/questions/20782400/how-to-remove-children-element-from-xml-in-java/20782520? Noredirect = 1 # 20782520 – vijayk

+0

@vijayk практически это тот же вопрос снова. Измените 'option' на' quest' и выберите индекс 0. –

0
if (ques.getName().equalsIgnoreCase("options")) { 
         List optList = ques.getChildren(); 
         for (int k = optList.size()-1; k < optList.size(); k++) { 
          Element option = (Element) optList.get(k); 
          if(option.getName().equalsIgnoreCase("option")){ 
           //read 
           option.getParentElement().removeChild("option"); 
          } 
         } 
        } 

просто сосредоточиться на петле и перебирать от последнего индекса -1, что я сделал в коде.

+0

bt удалить только первый элемент опции. – vijayk

+0

вы пробовали? он удаляет последний –

+0

'yes i hd. – vijayk

 Смежные вопросы

  • Нет связанных вопросов^_^