这是我的代码,我就想XML中CDATA的QueryReason的内容,生成新的XML,可是怎么都搞不赢,大神棒棒我啊。
public class XMLTest {
public static void main(String args[]) throws DocumentException {
XMLTest test = new XMLTest();
Element element;
try {
element = test.testGetRoot("D:\\XML\\20151020162738980140.xml");
String newfileName = "D:\\XML\\20151020162738980140" + "-新.xml";
formatXml(element, "GBK", false, newfileName);
} catch (Exception e) {
e.printStackTrace();
}
}
public Element testGetRoot(String pathName) throws Exception {
SAXReader sax = new SAXReader();// 创建一个SAXReader对象
File xmlFile = new File(pathName);// 根据指定的路径创建file对象
Document document = sax.read(xmlFile);// 获取document对象,如果文档无节点,则会抛出Exception提前结束
Element root = document.getRootElement();// 获取根节点
this.getNodes(root);// 从根节点开始遍历所有节点
return root;
}
/**
* 递归遍历方法
*
* @param element
* @throws Exception
*/
public void getNodes(Element node) throws Exception {
// 当前节点的名称、文本内容和属性
System.out.println("当前节点名称:" + node.getName());// 当前节点名称
System.out.println("当前节点的内容:" + node.getTextTrim());// 当前节点的内容
//这里想通过遍历CDATA的内容后去掉QueryReason的值,可是怎么都去不掉
if("ReportMessage".equals(node.getName()) && !"".equals(node.getTextTrim())){
node =DocumentHelper.parseText(node.getTextTrim()).getRootElement();
this.getNodes(node);
}
// 递归遍历当前节点所有的子节点
List<Element> listElement = node.elements();// 所有一级子节点的list
for (Element e : listElement) {// 遍历所有一级子节点
if ("QueryReason".equals(e.getName())) {
e.setText("");
}
this.getNodes(e);// 递归
}
}
public static void formatXml(Element element, String charset,
boolean istrans, String newfileName) throws Exception {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(charset);
XMLWriter xw = new XMLWriter(new FileOutputStream(newfileName), format);
xw.startDocument();
xw.setEscapeText(istrans); // istrans false这样&符号就不会被转义了
try {
xw.write(element);
xw.flush();
xw.close();
} catch (IOException e) {
System.out.println("格式化XML文档发生异常,请检查!");
e.printStackTrace();
}
}
<?xml version="1.0" encoding="GBK"?>
<CFX>
<HEAD>
<SRC>B0000000000001</SRC>
</HEAD>
<MSG>
<ReportMessage>
<![CDATA[
<ReportMessage>
<LatestMonthQueryorgSum>
<QueryReason>02|贷款审批</QueryReason>
<Sum>0</Sum>
</LatestMonthQueryorgSum>
</ReportMessage>]]></ReportMessage>
</MSG>
</CFX>