前端之家收集整理的这篇文章主要介绍了
xml解析之dom,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package cn.tong.jaxp;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class TestJaxp {
public static void main(String[] args) throws ParserConfigurationException,SAXException,IOException,TransformerException {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse("src/person.xml");
NodeList list = document.getElementsByTagName("name");
for(int i = 0 ; i < list.getLength() ; i++){
Node name1 = list.item(i);
System.out.println(name1.getTextContent().toString());
}
NodeList p1 = document.getElementsByTagName("p1");
for(int i = 0 ; i < p1.getLength() ; i++){
Node p = p1.item(i);
Element el_gender = document.createElement("gender");
el_gender.setTextContent( i%2 == 0 ? "男" : "女" );
p.appendChild(el_gender);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new DOMSource(document),new StreamResult("src/person.xml"));
}
}