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 {
// 查询所有name元素的值
//创建解析器工程
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
//创建解析器
DocumentBuilder builder = builderFactory.newDocumentBuilder();
//解析xml返回document
Document document = builder.parse("src/person.xml");
//得到name元素
NodeList list = document.getElementsByTagName("name");
for(int i = 0 ; i < list.getLength() ; i++){
Node name1 = list.item(i);
//得到name元素的值
System.out.println(name1.getTextContent().toString());
}
NodeList p1 = document.getElementsByTagName("p1");
for(int i = 0 ; i < p1.getLength() ; i++){
Node p = p1.item(i);
//得到name元素的值
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"));
}
}
xml解析之dom
最新推荐文章于 2024-08-14 11:08:07 发布