xml和string和xml和CDATA的用法

xml和string和xml和CDATA的用法


StringToXml.java


import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;


public class StringToXml {
public static void xmlTest(){
String xml="" +
"" +
"" +
"MyName" +
"" +                                                //要注意   CDATA   格式的写法哦,不要缺少"<"符号
"" +
"
";

//输出这个String类型的XML
System.out.println("输出这个String类型的XML:\n"+xml);

//将String的XML转化为XML类型并输出
Document document=null;
try {
document = DocumentHelper.parseText(xml);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}    
//为节点增加子节点
document.getRootElement().addElement("testNode_Add");
document.getRootElement().addElement("testNode_Add2");

//获取子节点并显示子节点的内容
System.out.println("\n获取子节点并显示子节点的内容:");
Element rt = document.getRootElement();
   Node nameNode=rt.selectSingleNode("/root/head/name");
   Node ageNode=rt.selectSingleNode("/root/head/age");
   rt.selectSingleNode("/root/testNode_Add").setText("实验新增节点");
   
   Element note2=(Element) rt.selectSingleNode("/root/testNode_Add2");
note2.addCDATA("实验CDATA节点内容");
   
   Node testNode_AddNode=rt.selectSingleNode("/root/testNode_Add");
   Node testNode_AddNode2=rt.selectSingleNode("/root/testNode_Add2");
   
   System.out.println("nameNode="+nameNode.getText());
   System.out.println("ageNode="+ageNode.getText());
   System.out.println("testNode_AddNode="+testNode_AddNode.getText());
   System.out.println("testNode_AddNode2="+testNode_AddNode2.getText());
   
   //将XML转化String
   String xml2=document.asXML();
   System.out.println(xml2);
   
   
   Document document2=null;
   SAXReader reader = new SAXReader();
   
   //将String转化为XML
StringReader stringReader = new StringReader(xml2.trim());
try {
document2 = reader.read(stringReader);

//XML转化为String
System.out.println("2"+document2.asXML());

} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//将XML格式化显示在操作台-默认是utf-8
OutputFormat outPutFormat=OutputFormat.createPrettyPrint();
outPutFormat.setEncoding("GBK");//如果要更改字符格式

XMLWriter xmlWriter=new XMLWriter(new OutputStreamWriter(System.out),outPutFormat);
try {
System.out.println("\n");
xmlWriter.write(document);
xmlWriter.flush();
System.out.println("\nxmlWriter.close();之后的代码都不会再运行");
xmlWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

public static void main(String [] args){
xmlTest();
}


}

你可能感兴趣的:(xml和string和xml和CDATA的用法)