这是 xml 文件。我想一次读取和写入这个 xml。
<quest ans="0">
<question file="image.png"><![CDATA[A quadrilateral must be a parallelogram if one pair of opposite sides is _____.]]></question>
</quest>
这是我读取和写入文件 attritube 的 java 代码。
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);
}
}
}
}
输出是
<quest ans="0">
<question file="dasd0">question0</question>
</quest>
但我想要
<quest ans="0">
<question file="dasd0"><![CDATA[question0]]></question>
</quest>
quest 属性 ans 是变化,问题属性文件也在变化,但主要问题不是改变它,而是没有 CDATA,我想用 CDATA 提问。