字符串格式的xml
<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"><channel><title>Java Tutorials and Examples</title><item><title><![CDATA[Java Tutorials]]></title><link>http://www.javacodegeeks.com/</link></item><item><title><![CDATA[Java Examples]]></title><link>http://examples.javacodegeeks.com/</link></item></channel><channel></channel></rss>
格式化的xml
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>Java Tutorials and Examples</title>
<item>
<title>
<![CDATA[Java Tutorials]]>
</title>
<link>http://www.javacodegeeks.com/</link>
</item>
<item>
<title>
<![CDATA[Java Examples]]>
</title>
<link>http://examples.javacodegeeks.com/</link>
</item>
</channel>
<channel></channel>
</rss>
完整代码:
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
/**
* @Author Daniel
* @Description java自带的类解析xml文件的常用API
**/
public class DomAPI {
static Document doc = null;
static Element element = null;
public static void main(String[] args) throws Exception {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><rss version=\"2.0\"><channel><title>Java Tutorials and Examples</title><item><title><![CDATA[Java Tutorials]]></title><link>http://www.javacodegeeks.com/</link></item><item><title><![CDATA[Java Examples]]></title><link>http://examples.javacodegeeks.com/</link></item></channel><channel></channel></rss>";
//建立一个解析器工厂
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//利用这个工厂来获得一个具体的解析器对象
DocumentBuilder db = dbf.newDocumentBuilder();
//传入解析类型,这里为字符串,如要传文件则是ocument doc=builder.parse(“data.xml")
doc = db.parse(new ByteArrayInputStream(xml.getBytes(Charset.defaultCharset())));
//获取第一个channel的Element对象
element = (Element) doc.getElementsByTagName("channel").item(0);
create();
// update();
// retrieve();
// delete();
}
public static void create() {
//创建一个新的标签
Element newElement = doc.createElement("Price");
//设置标签的内容
newElement.setTextContent("$50.00");
//将此标签添加到channel下面
element.appendChild(newElement);
//创建一个空的属性名
Attr nullAttribute = doc.createAttribute("id");
//为当前的element加上属性
element.setAttributeNode(nullAttribute);
//上面两句代码的效果等同于element.setAttribute("id","")
System.out.println(getResult(doc));
}
public static void update() {
//设置channel的属性与属性值
element.setAttribute("Type", "myAttribute");
System.out.println(getResult(doc));
}
public static void retrieve() {
//得到某个标签的个数
int channelCount = doc.getElementsByTagName("channel").getLength();//2
//获取到第一个channel中的第一个item中第一个title的文本值
String text = ((Element) (((Element) (doc.getElementsByTagName("channel").item(0))).getElementsByTagName("item").item(0))).getElementsByTagName("title").item(0).getTextContent();
//判断第二个channel是否为单标签
boolean flag = doc.getElementsByTagName("channel").item(1).getTextContent() == "" ? true : false;
//整个xml的根节点的Element对象
Element documentElement = doc.getDocumentElement();
//获取元素名
String tagName = element.getTagName();
//获取channel中属性Type的值
String value = ((Element) doc.getElementsByTagName("rss").item(0)).getAttribute("version");
System.out.println("channel的个数:" + channelCount + "\ntitle的内容:" + text + "\n是否为单标签:" + flag + "\n该文件的根节点为:" + documentElement.getTagName() + "\n当前Element的标签为:" + tagName + "\n属性值为:" + value);
}
public static void delete() {
//删除第一个channel中的第一个item标签以及它的子标签
element.removeChild(((Element) (doc.getElementsByTagName("channel").item(0))).getElementsByTagName("item").item(0));
System.out.println(getResult(doc));
}
//将xml转换成字符串
public static String getResult(Document xml) {
Transformer tf = null;
try {
tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
Writer out = new StringWriter();
tf.transform(new DOMSource(xml), new StreamResult(out));
//删除第一行的注释标签
return out.toString().substring(out.toString().indexOf(">") + 1);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
return "ERROR!";
}
}