最代碼廣告位
software0116的gravatar頭像
software01162012-10-13 17:45:24

Jdom、Dom4j、W3c、String相互轉換大全以及取Xml的屬性值、設置Xml的屬性值、刪除Xm屬性值

Jdom、Dom4j、W3c、String相互轉換大全以及取Xml的屬性值、設置Xml的屬性值、刪除Xm屬性值

package com.zuidaima.xml;
import java.io.CharArrayReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.xerces.dom.DocumentImpl;
import org.apache.xerces.parsers.DOMParser;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.apache.xpath.XPathAPI;
import org.jdom.input.DOMBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class XmlChange {

	/**
	 * 將document對象,轉換成字符串數據
	 * @param dom
	 * @return
	 */
	public static String dom2String(Document dom)
	// 將document對象,轉換成字符串數據。
	{
		String aa = new String();
		try {
			StringWriter ss = new StringWriter();
			OutputFormat format = new OutputFormat(dom); // Serialize DOM
			format.setEncoding("GB2312");
			XMLSerializer serial = new XMLSerializer(ss, format);
			serial.asDOMSerializer(); // As a DOM Serializer
			serial.serialize(dom.getDocumentElement());
			aa = ss.toString();
			ss.flush();
			ss.close();
		} catch (Exception e) {
			// return false;
		}
		return aa;
	}

	/**
	 * 字符串轉換成document
	 * 
	 * @param XMLData
	 * @return
	 */
	public static Document string2Dom(String XMLData)
	// 解析字符串xml數據,生成document
	{
		// System.out.println("xml:"+XMLData);
		Document dom = new DocumentImpl();
		try {
			InputSource source = new InputSource(new CharArrayReader(XMLData
					.toCharArray()));
			System.out.println("-----888888==" + source);
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			dom = docBuilder.parse(source);
			System.out.println("-----888888==" + dom);
		} catch (Exception e) {
			dom = null;
		} finally {
			return dom;
		}
	}

	/**
	 * 解析字符串xml數據,生成document,過濾xml中間的空格
	 * 
	 * @param data
	 * @param isSpace
	 * @return
	 * @throws IOException
	 * @throws SAXException
	 */

	public static Document string2Dom(String data, boolean isSpace)
			throws IOException, SAXException
	// 解析字符串xml數據,生成document,過濾xml中間的空格
	{
		if (isSpace) {
			DOMParser parser = new DOMParser();
			StringReader sr = new StringReader(data);
			InputSource is = new InputSource(sr);
			parser.parse(is);
			sr.close();
			return parser.getDocument();
		} else {
			return null;
		}
	}

	/**
	 * 實現dom4j向org.w3c.dom.Document的轉換
	 * 
	 * @param doc
	 * @return
	 * @throws Exception
	 */
	public static org.w3c.dom.Document dom4j2W3c(Document doc) throws Exception {
		if (doc == null) {
			return (null);
		}
		java.io.StringReader reader = new java.io.StringReader(doc.toString());
		org.xml.sax.InputSource source = new org.xml.sax.InputSource(reader);
		javax.xml.parsers.DocumentBuilderFactory documentBuilderFactory = javax.xml.parsers.DocumentBuilderFactory
				.newInstance();
		javax.xml.parsers.DocumentBuilder documentBuilder = documentBuilderFactory
				.newDocumentBuilder();
		return (documentBuilder.parse(source));
	}

	/**
	 * 
	 * 實現 org.w3c.dom.Document到dom4j的轉換
	 * 
	 * @param doc
	 * @return
	 * @throws Exception
	 */
	public static org.dom4j.Document parse(org.w3c.dom.Document doc)
			throws Exception {
		if (doc == null) {
			return (null);
		}
		org.dom4j.io.DOMReader xmlReader = new org.dom4j.io.DOMReader();
		return (xmlReader.read(doc));
	}

	/**
	 * 
	 * 實現 org.w3c.dom.Document到jdom的轉換
	 * 
	 * @param doc
	 * @return
	 * @throws Exception
	 */
	public static org.jdom.Document convertToJDOM(org.w3c.dom.Document doc)
			throws Exception {
		if (doc == null) {
			return (null);
		}
		DOMBuilder builder = new DOMBuilder();
		org.jdom.Document jdomDoc = builder.build(doc);
		return jdomDoc;

	}

	/**
	 * 根據tagName,attributeName從xml中取得取得相應Node屬性值 可能有多個tagName定義的Node,取第一個
	 * 
	 * @param dom
	 * @param tagName
	 * @attributeName
	 * @return Attribute;
	 */
	public static String getAttributeValueFromDom(Document dom, String tagName,
			String attributeName) {
		String result = "";
		if (dom != null && tagName != null && !tagName.trim().equals("")
				&& attributeName != null && !attributeName.trim().equals("")) {
			NodeList nodeList = null;
			Node node = null;
			nodeList = dom.getElementsByTagName(tagName.trim());
			if (nodeList != null && nodeList.getLength() > 0) {
				/**
				 * xml中可能有多個tagName定義的Node,取第一個
				 */
				node = nodeList.item(0);
				if (node != null) {
					result = ((Element) node).getAttribute(attributeName);
					result = result == null ? "" : result.trim();
				}
			}
		}
		return result;
	}

	/**
	 * 設置xml節點屬性值
	 * 
	 * @param dom
	 * @param tagName
	 * @param attributeName
	 * @param value
	 * @return
	 */
	public static boolean setAttributeValueFromDom(Document dom,
			String tagName, String attributeName, String value) {
		boolean result = false;
		if (dom != null && tagName != null && !tagName.trim().equals("")
				&& attributeName != null && !attributeName.trim().equals("")) {
			NodeList nodeList = null;
			Node node = null;
			nodeList = dom.getElementsByTagName(tagName.trim());
			if (nodeList != null && nodeList.getLength() > 0) {
				/**
				 * xml中可能有多個tagName定義的Node,取第一個
				 */
				node = nodeList.item(0);
				if (node != null) {
					((Element) node).setAttribute(attributeName, value);
					result = true;
				}
			}
		}
		return result;
	}

	/**
	 * 根據tagName從xml中取得取得相應Node值
	 * 
	 * @param dom
	 * @param tagName
	 * @return
	 */
	public static String getNodeValueFromDom(Document dom, String tagName) {
		String result = "";
		try {
			if (dom != null && tagName != null && !tagName.trim().equals("")) {
				NodeList nodeList = null;
				Node node = null;
				nodeList = XPathAPI.selectNodeList(dom, tagName.trim());// dom.getElementsByTagName(tagName.trim());
				if (nodeList != null && nodeList.getLength() > 0) {
					/**
					 * xml中可能有多個tagName定義的Node,取第一個
					 */
					node = nodeList.item(0);
					if (node != null) {
						node = node.getFirstChild();
						if (node != null)
							result = node.getNodeValue();
						result = result == null ? "" : result.trim();
					}
				}
			}
		} catch (Exception e) {
			System.out.println(" getNodeValueFromDom 出錯 = " + e.toString());
			e.printStackTrace();
		}
		return result;
	}

	public static String getTagValueByTagName(Document dom, String tagName) {
		String result = "";
		try {
			if (dom != null && tagName != null && !tagName.trim().equals("")) {
				NodeList nodeList = null;
				Node node = null;
				if (dom.getElementsByTagName(tagName.trim()) != null) {
					nodeList = dom.getElementsByTagName(tagName.trim());
					if (nodeList.item(0) != null) {
						node = nodeList.item(0);
						if ((node.getChildNodes()).item(0).getNodeValue() != null) {
							result = (node.getChildNodes()).item(0)
									.getNodeValue().trim();
						}
					}
				}
			}
		} catch (Exception e) {
			System.out.println(" getNodeValueFromDom 出錯 = " + e.toString());
			e.printStackTrace();
		}
		return result;
	}
}

 


騎著豬豬去逛街編輯于2013-12-27 11:17:59


最代碼官方編輯于2014-8-22 9:40:30


打賞

文件名:XML.zip,文件大小:1966K下載
  • /
      • /XML
        • /XML/.classpath
          • /XML/.myeclipse
          • /XML/.mymetadata
          • /XML/.project
            • /XML/.settings
              • /XML/.settings/.jsdtscope
              • /XML/.settings/org.eclipse.jdt.core.prefs
              • /XML/.settings/org.eclipse.wst.jsdt.ui.superType.container
              • /XML/.settings/org.eclipse.wst.jsdt.ui.superType.name
    頂部客服微信二維碼底部
    >掃描二維碼關注最代碼為好友掃描二維碼關注最代碼為好友
    2008大乐透走势图