문제

This is xml file .I want to read and write this xml at a time.

<quest ans="0"> 
    <question file="image.png"><![CDATA[A quadrilateral must be a parallelogram if one pair of opposite sides is _____.]]></question>
</quest>

this is my java code to read and write the file attritube.

String path="D://test//N2086_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());
                            //write
                        ques.setText("question"+a);
                    }
                }
            } 
          }  

output is

<quest ans="0"> 
    <question file="dasd0">question0</question>
</quest>

but i want

<quest ans="0"> 
<question file="dasd0"><![CDATA[question0]]></question>
</quest>

quest attribute ans is change and question attribute file is also change but main question is not change it change but without CDATA and I want question with CDATA.

도움이 되었습니까?

해결책

If you want the quest0 to be enclosed with CDATA markup, then create a CDATA content item:

Change the section:

                if(ques.getName().equalsIgnoreCase("question")){
                    //read 
                    System.out.println(ques.getTextTrim());
                        //write
                    ques.setText("question"+a);
                }

to look like:

                if(ques.getName().equalsIgnoreCase("question")){
                    //read 
                    System.out.println(ques.getTextTrim());
                        //write
                    ques.removeContent();
                    ques.addContent(new CDATA("question"+a));
                }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top