用org.w3c.dom和javax.xml处理XML

为了少引入几个包,用JAVA标配的org.w3c.dom和javax.xml来处理XML

public static void main(String[] args){
		String activtyRecord = "<activityRecord></activityRecord>";
		
		Document xmlDoc=null;		
		try {
			 xmlDoc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(activtyRecord.getBytes()));	
			Node rootNode = xmlDoc.getChildNodes().item(0);
		
	
		Element newActivity = xmlDoc.createElement("activity");
		newActivity.setAttribute("name", "activityName");
		
		Element eRole = xmlDoc.createElement("role");
		eRole.appendChild(xmlDoc.createTextNode("role2"));
		Element eUserName = xmlDoc.createElement("userName");
		eUserName.appendChild(xmlDoc.createTextNode("userName2"));
		Element eDecision = xmlDoc.createElement("decision");
		eDecision.appendChild(xmlDoc.createTextNode("decision2"));
		Element eDate = xmlDoc.createElement("date");
		eDate.appendChild(xmlDoc.createTextNode("date2"));
		
		newActivity.appendChild(eRole);
		newActivity.appendChild(eUserName);
		newActivity.appendChild(eDecision);
		newActivity.appendChild(eDate);
		
		rootNode.appendChild(newActivity);
		

		DOMSource domSource = new DOMSource(xmlDoc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        writer.flush();

        System.out.println(writer);

			
		} catch (Exception e) {
			e.printStackTrace();
		}
		

	}

 还真是繁琐。。。

打印结果如下:

<?xml version="1.0" encoding="UTF-8"?>
<activityRecord><activity name="activityName"><role>role2</role><userName>userName2</userName><decision>decision2</decision><date>date2</date></activity></activityRecord>

你可能感兴趣的:(xml)