`

XmlHelper

    博客分类:
  • Java
 
阅读更多
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;

public class XmlHelper {
    static public String EncodeXML(String sString)
    {
        sString = util.ReplaceText(sString, "&", "&");
        sString = util.ReplaceText(sString, "<", "&lt;");
        sString = util.ReplaceText(sString, ">", "&gt;");
        sString = util.ReplaceText(sString, "'", "&apos;");
        sString = util.ReplaceText(sString, "\"", "&quot;");
        
        return sString;   	
    }

    public String ReadSingleElementValue(
		String sXmlFile,
		String sPath) throws Exception
	{
		DocumentBuilderFactory oDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder oDocumentBuilder = oDocumentBuilderFactory.newDocumentBuilder();
		Document oDoc = oDocumentBuilder.parse(getClass().getResourceAsStream(sXmlFile));
		
		return GetElementNode(oDoc, sPath).getFirstChild().getNodeValue();
	}
	
    public String ReadSingleElementAttribute(
		String sXmlFile,
		String sPath,
		String sAttribute) throws Exception
	{
		DocumentBuilderFactory oDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder oDocumentBuilder = oDocumentBuilderFactory.newDocumentBuilder();
		Document oDoc = oDocumentBuilder.parse(getClass().getResourceAsStream(sXmlFile));
		
		return GetElementNode(oDoc, sPath).getAttribute(sAttribute);
	}

    public HashMap ReadElementsAttribute(
		String sXmlFile,
		String sPath,
		String sKeyAttribute,
		String sValueAttribute) throws Exception
	{
		DocumentBuilderFactory oDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder oDocumentBuilder = oDocumentBuilderFactory.newDocumentBuilder();
		Document oDoc = oDocumentBuilder.parse(this.getClass().getClassLoader().getResourceAsStream(sXmlFile));
		
		HashMap oResult = new HashMap();
		
		//NodeList oNodeList = oDoc.getElementsByTagName("Error");
		NodeList oNodeList = GetElementNodeList(oDoc, sPath);
		
		for (int i=0 ; i<oNodeList.getLength() ; i++)
		{
			NamedNodeMap oAttributes = oNodeList.item(i).getAttributes();
			String sKey = oAttributes.getNamedItem(sKeyAttribute).getNodeValue();
			String sValue = oAttributes.getNamedItem(sValueAttribute).getNodeValue();
			oResult.put(sKey, sValue);
		}
		
		return oResult;
	}

    public Element GetElementNode(Document oXmlDoc, String sPath)
	{
		String[] oTagList = sPath.split("/");
		Element oElement = (Element)oXmlDoc.getElementsByTagName(oTagList[0]).item(0);
		for (int i=1 ; i<oTagList.length ; i++)
		{
			oElement = (Element)oElement.getElementsByTagName(oTagList[i]).item(0);
		}	
		return oElement;
	}

    public NodeList GetElementNodeList(Document oXmlDoc, String sPath)
	{
		String[] oTagList = sPath.split("/");
		if (oTagList.length == 1)
		{
			return oXmlDoc.getElementsByTagName(oTagList[0]);
		}else
		{
			Element oElement = (Element)oXmlDoc.getElementsByTagName(oTagList[0]).item(0);
			for (int i=1 ; i<oTagList.length ; i++)
			{
				NodeList oNodeList = oElement.getElementsByTagName(oTagList[i]);
				if (i == oTagList.length - 1)
				{
					return oNodeList;
				}else
				{
					oElement = (Element)oNodeList.item(0);					
				}
			}			
		}
		return null;
	}
    
    public Document constructDocumentFromXmlString(String xml){
    	Document output = null;
    	try{
    		if(!util.isEmpty(xml)){
	    		ByteArrayInputStream xmlStream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
	    		
				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		
			    // Set namespaceAware to true to get a DOM Level 2 tree with nodes
			    // containing namesapce information.  This is necessary because the
			    // default value from JAXP 1.0 was defined to be false.
			    dbf.setNamespaceAware(true);
	
			    dbf.setValidating(false);
			    dbf.setIgnoringComments(true);
			    dbf.setIgnoringElementContentWhitespace(false);
			    dbf.setCoalescing(true);
	
			    DocumentBuilder db = dbf.newDocumentBuilder();
			    output = db.parse(xmlStream);
    		}
		} catch(Exception e){
			util.debug("Error in XML: " + xml);
			e.printStackTrace();
			output = null;
		}
		return output;
    }
    
    public Document createDocument(){
    	return this.constructDocumentFromXmlString("<documentRoot></documentRoot>");
    }
    
    public String convertDocumentToString(Document document){    	
        return convertDocumentToString(document, false);
    }
    
    public String convertDocumentToString(Document document, boolean omitXMLDeclaration){
    	if (util.isEmpty(document)) return null;
    	String output = null;
    	try{
	    	OutputFormat format = new OutputFormat(document);
	    	format.setOmitXMLDeclaration(omitXMLDeclaration);
	        StringWriter strOut = new StringWriter();
	        XMLSerializer xmls = new XMLSerializer(strOut, format);
	        xmls.serialize(document.getDocumentElement());
	        output = strOut.toString();
    	} catch(Exception e){
    		e.printStackTrace();
    	}
        return output;
    }
    
    public Element getChild(Element element, String childElementName){
    	return(Element)element.getElementsByTagName(childElementName).item(0);
    }
    
    public String getChildText(Element element, String childElementName){
    	String output = "";
    	try{
    		output = element.getElementsByTagName(childElementName).item(0).getFirstChild().getNodeValue();
    	} catch(Exception e){
    	}
    	return output;
    }
    
    public String getText(Element element){
    	String output = "";
    	try{
    		output = element.getFirstChild().getNodeValue();
    	} catch(Exception e){
    	}
    	return output;
    }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics