JAVA:DOM解析XML和修改XML

 JAVA:DOM解析XML和修改XML

一:工程结构:

 二:类:XMLPARSER

package com.demo.xml;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLPARSER {
	

	@Test
	public void parserxml() throws Exception{
		

		DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance();

		DocumentBuilder documentBuilder = builderfactory.newDocumentBuilder();

		Document document = documentBuilder.parse("book.xml");
	
		NodeList nodelist = document.getElementsByTagName("xsd:shuming");
		
		Node node = nodelist.item(0);
		
		String textContent = node.getTextContent();
		
		System.out.println(textContent);
	
	}
	
	
	/*
	 * 修改XML
	 * */
	@Test
	public void modifyXML() throws Exception {
		
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
		
		DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
		
		Document document = documentBuilder.parse("book.xml");
		
		NodeList nodeList = document.getElementsByTagName("xsd:jiage");
		
		Node item = nodeList.item(0);
		
		item.setTextContent("12345");
	
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		
		Transformer transformer = transformerFactory.newTransformer();
				
		Source xmlSource = new DOMSource(document);
		
		Result outputTarget = new StreamResult("book.xml");
		
		transformer.transform(xmlSource, outputTarget);
		
		System.out.print("modify over!");
		
		
	}
}

 

发布了38 篇原创文章 · 获赞 25 · 访问量 6万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术工厂 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览