当前位置:首页 > 开发 > 编程语言 > XML > 正文

Java XML Read Write org.w3c.dom

发表于: 2015-05-05   作者:Colin_Davis   来源:转载   浏览:
摘要:      Java 自带的 XML 操作, 留着备用   <?xml version="1.0" encoding="UTF-8" standalone="no"?> <items> <item UUID="9da9da4e-b694-4d5f-98

 

   Java 自带的 XML 操作, 留着备用

 

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<items>
<item UUID="9da9da4e-b694-4d5f-988c-7dcb32f548e1">
<date>0.09196741716363777</date>
<time>7718945087234434250</time>
<text>1430765505937</text>
</item>
<item UUID="8c52774c-030b-425a-8a3f-933c061bb75e">
<date>0.009140362233125865</date>
<time>6997050766083944829</time>
<text>1430765505937</text>
</item>
<item UUID="931938fa-ce1e-49d2-a886-4ec5bae1bdd8">
<date>0.24709196045848147</date>
<time>3235439044183085217</time>
<text>1430765505937</text>
</item>
</items>

 

   (<)小于号会自动转化为 (&lt;) HTML标记, (>)大于号会自动转化为 (&gt;)   

 

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<items>
<item UUID="f3a0ef1c-c697-4571-a6a3-7a4984d554d2">
<date>0.36942465313752504</date>
<time>-8059914408081165808</time>
<text>1430765657484</text>
<tag>&lt;tag&gt;value&lt;/tag&gt;</tag>
</item>
<item UUID="3c02bfcc-23e9-4cfc-ab92-7012c1bc8f7b">
<date>0.0709377155157227</date>
<time>-5406396638998085219</time>
<text>1430765657484</text>
<tag>&lt;tag&gt;value&lt;/tag&gt;</tag>
</item>
<item UUID="c68bf6ae-e6eb-4ed8-ac16-908d9c1cd98a">
<date>0.4357969220901605</date>
<time>-1198327362916383684</time>
<text>1430765657484</text>
<tag>&lt;tag&gt;value&lt;/tag&gt;</tag>
</item>
</items>

 

 

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

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;

/**
 * @author Colin <br />
 * 
 */
public class XML {

	/**
	 * 
	 */
	private XML() {
		// TODO Auto-generated constructor stub
	}
	
	private static final class XMLSingle {
		private static final XML startup = new XML();
	}
	
	public static XML getInstance() {
		return XMLSingle.startup;
	}

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {

		//getInstance().OutputXML();
		
		StringBuilder builder = new StringBuilder( System.getProperty( "user.dir" ) + File.separator + "data" + File.separator );
		//builder.append( "xml-7951f6c6-7242-4e5d-a0e6-38e0677fcc6b.xml" );
		builder.append( "xml-dc1348e6-31a8-4f75-9283-b69435cab9f4.xml" );
		String path = builder.toString();
		
		//getInstance().ReadXML( path );
		
		getInstance().ReadItem( path, "fc911e97-55cb-4060-8eb2-395933330b46" );
	}
	
	public void ReadItem( String xmlPath, String uuid ) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
		this.ReadItem( new File( xmlPath ), uuid );
	}
	public void ReadItem( File xmlFile, String uuid ) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		
		Document document = builder.parse( xmlFile );
		
		XPath xpath = XPathFactory.newInstance().newXPath();
		XPathExpression expression = xpath.compile( "/items/item[@UUID='" + uuid + "']" );
		Node node = (Node) expression.evaluate( document, XPathConstants.NODE );
		System.out.println( node.getNodeName() + " --> " + node.getTextContent() );
	}
	
	/**
	 * 
	 * @param xmlFile
	 * @throws ParserConfigurationException 
	 * @throws IOException 
	 * @throws SAXException 
	 */
	public void ReadXML( String xmlPath ) throws ParserConfigurationException, SAXException, IOException {
		this.ReadXML( new File( xmlPath ) );
	}
	
	/**
	 * 
	 * @param xmlFile
	 * @throws ParserConfigurationException 
	 * @throws IOException 
	 * @throws SAXException 
	 */
	public void ReadXML( File xmlFile ) throws ParserConfigurationException, SAXException, IOException {
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		
		Document document = builder.parse( xmlFile );
		
		Element items = document.getDocumentElement();
		
		NodeList list = items.getElementsByTagName( "tag" );
		for ( int i = 0, l = list.getLength(); l > i; ++i ) {
			Node item = list.item( i );
			System.out.println( item.getTextContent() + " --> " + item.getParentNode().getNodeName() );
		}
		
		for ( Node item : this.ItemNodes( items ) ) {
			System.out.println( item.getNodeName() + " --> " + item.getNodeType() + " ==> " + item.getTextContent() );
		}
	}
	
	private List<Node> ItemNodes( Element root ) {
		
		List<Node> nodes = new ArrayList<Node>( 10 );
		
		NodeList list = root.getChildNodes();
		for ( int i = 0, l = list.getLength(); l > i; ++i ) {
			Node item = list.item( i );
			if ( item.getNodeType() == Node.ELEMENT_NODE && item.getNodeName().equals( "item" ) ) {
				nodes.add( item );
			}
		}
		
		return nodes;
	}
	
	/**
	 * 
	 * @throws ParserConfigurationException
	 * @throws TransformerFactoryConfigurationError
	 * @throws TransformerException
	 * @return
	 */
	public String OutputXML() throws ParserConfigurationException, TransformerFactoryConfigurationError, TransformerException {
		
		String path = System.getProperty( "user.dir" ) + File.separator + "data" + File.separator;
		File xmlFile = new File( path, "xml-" + UUID.randomUUID() + ".xml" );
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		
		Document document = builder.newDocument();
		{
			Element root = document.createElement( "items" );
			{
				for ( byte i = 0, l = 10; l > i; ++i )
					root.appendChild( this.CreateItemNode( document ) );
			}
			document.appendChild( root );
		}
		
		Transformer transformer = TransformerFactory.newInstance().newTransformer();
		transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
		transformer.setOutputProperty( OutputKeys.METHOD, "xml" );
		transformer.setOutputProperty( OutputKeys.ENCODING, "UTF-8" );
		transformer.setOutputProperty( OutputKeys.STANDALONE, "yes" );
		transformer.setOutputProperty( OutputKeys.VERSION, "1.0" );
		transformer.transform( new DOMSource( document ), new StreamResult( xmlFile ) );
		
		return xmlFile.getAbsolutePath();
	}
	
	/**
	 * 
	 * @param document
	 * @return
	 */
	private Element CreateItemNode( Document document ) {
		
		Element item = document.createElement( "item" );
		item.setAttribute( "UUID", UUID.randomUUID().toString() );
		
		item.appendChild( this.CreateTextNode( document, "date", Math.random() + "" ) );
		item.appendChild( this.CreateTextNode( document, "time", new Random().nextLong() + "" ) );
		item.appendChild( this.CreateTextNode( document, "text", System.currentTimeMillis() + "" ) );
		item.appendChild( this.CreateTextNode( document, "tag", "<tag>value</tag>" ) );
		item.appendChild( this.CreateTextNode( document, "url", "http://pan.baidu.com/disk/home#path=%252FCode" ) );
		item.appendChild( this.CreateTextNode( document, "sign", "`~1!@#$%^&*()_+=-{}[]/\\|\"" ) );
		
		return item;
	}
	
	/**
	 * 
	 * @param document
	 * @param tag
	 * @param value
	 * @return
	 */
	private Element CreateTextNode( Document document, String tag, String value ) {
		Element element = document.createElement( tag );
		element.appendChild( document.createTextNode( value ) );
		return element;
	}

}

 

Java XML Read Write org.w3c.dom

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号