- 浏览: 259120 次
- 性别:
- 来自: 济南
文章分类
最新评论
-
MR3CHEN:
gaojiehigh 写道正在找这样的方法,我不过发现了一个问 ...
Java删除文件夹以及文件夹下的子目录与文件 -
gaojiehigh:
正在找这样的方法,我不过发现了一个问题,嘿嘿
[img][/i ...
Java删除文件夹以及文件夹下的子目录与文件 -
mimang2007110:
这个方法很实用,刚才适用了一下,挺好的,多谢
Java删除文件夹以及文件夹下的子目录与文件 -
sblig:
int icount = toKenizer.countT ...
Java拆分字符串返回数组 -
haiyangyiba:
文件夹中有中文文件不行,
Java解压缩ZIP文件同时包含Jar包解决ZIP包中含有中文名称信息的文件
package com.yc.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.crimson.tree.XmlDocument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
/**
* Utilities methods to simplify dealing with JAXP & DOM XML parsing
*
* @author <a href="mailto:jonesde@ofbiz.org">David E. Jones</a>
* @version $Revision: 1.1 $
* @since 2.0
*/
public class UtilXml
{
public static final String module = UtilXml.class.getName();
public static String writeXmlDocument(Document document) throws java.io.IOException
{
if (document == null)
{
Debug.logWarning("[UtilXml.writeXmlDocument] Document was null, doing nothing", module);
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
writeXmlDocument(bos, document);
String outString = bos.toString("UTF-8");
if (bos != null)
bos.close();
return outString;
}
public static void writeXmlDocument(String filename, Document document) throws java.io.FileNotFoundException, java.io.IOException
{
if (document == null)
{
Debug.logWarning("[UtilXml.writeXmlDocument] Document was null, doing nothing", module);
return;
}
if (filename == null)
{
Debug.logWarning("[UtilXml.writeXmlDocument] Filename was null, doing nothing", module);
return;
}
File outFile = new File(filename);
FileOutputStream fos = null;
fos = new FileOutputStream(outFile);
try
{
writeXmlDocument(fos, document);
}
finally
{
if (fos != null)
fos.close();
}
}
public static void writeXmlDocument(OutputStream os, Document document) throws java.io.IOException
{
if (document == null)
{
Debug.logWarning("[UtilXml.writeXmlDocument] Document was null, doing nothing", module);
return;
}
if (os == null)
{
Debug.logWarning("[UtilXml.writeXmlDocument] OutputStream was null, doing nothing", module);
return;
}
//todo:xml序列化需要改进
// if(document instanceof XmlDocument) {
//Crimson writer
XmlDocument xdoc = (XmlDocument) document;
xdoc.write(os);
// }
// else {
// // Xerces writer
// OutputFormat format = new OutputFormat(document);
// format.setIndent(2);
//
// XMLSerializer serializer = new XMLSerializer(os, format);
// serializer.asDOMSerializer();
// serializer.serialize(document.getDocumentElement());
// }
}
public static Document readXmlDocument(String content) throws SAXException, ParserConfigurationException, java.io.IOException
{
return readXmlDocument(content, true);
}
public static Document readXmlDocument(String content,String charSet) throws SAXException, ParserConfigurationException, java.io.IOException
{
return readXmlDocument(content, true,charSet);
}
public static Document readXmlDocument(String content, boolean validate) throws SAXException, ParserConfigurationException, java.io.IOException
{
if (content == null)
{
Debug.logWarning("[UtilXml.readXmlDocument] content was null, doing nothing", module);
return null;
}
ByteArrayInputStream bis = new ByteArrayInputStream(content.getBytes("UTF-8"));
return readXmlDocument(bis, validate, "Internal Content");
}
public static Document readXmlDocument(String content, boolean validate,String charSet) throws SAXException, ParserConfigurationException, java.io.IOException
{
if (content == null)
{
Debug.logWarning("[UtilXml.readXmlDocument] content was null, doing nothing", module);
return null;
}
ByteArrayInputStream bis = new ByteArrayInputStream(content.getBytes(charSet));
return readXmlDocument(bis, validate, "Internal Content");
}
public static Document readXmlDocument(URL url) throws SAXException, ParserConfigurationException, java.io.IOException
{
return readXmlDocument(url, true);
}
public static Document readXmlDocument(URL url, boolean validate) throws SAXException, ParserConfigurationException, java.io.IOException
{
if (url == null)
{
Debug.logWarning("[UtilXml.readXmlDocument] URL was null, doing nothing", module);
return null;
}
// System.out.println(url);
return readXmlDocument(url.openStream(), validate, url.toString());
}
public static Document readXmlDocument(InputStream is) throws SAXException, ParserConfigurationException, java.io.IOException
{
return readXmlDocument(is, true, null);
}
public static Document readXmlDocument(InputStream is, boolean validate, String docDescription) throws SAXException, ParserConfigurationException, java.io.IOException
{
if (is == null)
{
Debug.logWarning("[UtilXml.readXmlDocument] InputStream was null, doing nothing", module);
return null;
}
Document document = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(validate);
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
if (validate)
{
LocalResolver lr = new LocalResolver(new DefaultHandler());
ErrorHandler eh = new LocalErrorHandler(docDescription, lr);
builder.setEntityResolver(lr);
builder.setErrorHandler(eh);
}
document = builder.parse(is);
return document;
}
public static Document makeEmptyXmlDocument()
{
return makeEmptyXmlDocument(null);
}
public static Document makeEmptyXmlDocument(String rootElementName)
{
Document document = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
// factory.setNamespaceAware(true);
try
{
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.newDocument();
}
catch (Exception e)
{
Debug.logError(e, module);
}
if (document == null)
return null;
if (rootElementName != null)
{
Element rootElement = document.createElement(rootElementName);
document.appendChild(rootElement);
}
return document;
}
/** Creates a child element with the given name and appends it to the element child node list. */
public static Element addChildElement(Element element, String childElementName, Document document)
{
Element newElement = document.createElement(childElementName);
element.appendChild(newElement);
return newElement;
}
/** Creates a child element with the given name and appends it to the element child node list.
* Also creates a Text node with the given value and appends it to the new elements child node list.
*/
public static Element addChildElementValue(Element element, String childElementName, String childElementValue, Document document)
{
Element newElement = addChildElement(element, childElementName, document);
newElement.appendChild(document.createTextNode(childElementValue));
return newElement;
}
/** Creates a child element with the given name and appends it to the element child node list.
* Also creates a CDATASection node with the given value and appends it to the new elements child node list.
*/
public static Element addChildElementCDATAValue(Element element, String childElementName, String childElementValue, Document document)
{
Element newElement = addChildElement(element, childElementName, document);
newElement.appendChild(document.createCDATASection(childElementValue));
return newElement;
}
/** Return a List of Element objects that have the given name and are
* immediate children of the given element; if name is null, all child
* elements will be included. */
public static List childElementList(Element element, String childElementName)
{
if (element == null)
return null;
List elements = new LinkedList();
Node node = element.getFirstChild();
if (node != null)
{
do
{
if (node.getNodeType() == Node.ELEMENT_NODE && (childElementName == null || childElementName.equals(node.getNodeName())))
{
Element childElement = (Element) node;
elements.add(childElement);
}
}
while ((node = node.getNextSibling()) != null);
}
return elements;
}
/** Return the first child Element with the given name; if name is null
* returns the first element. */
public static Element firstChildElement(Element element, String childElementName)
{
if (element == null)
return null;
// get the first element with the given name
Node node = element.getFirstChild();
if (node != null)
{
do
{
if (node.getNodeType() == Node.ELEMENT_NODE && (childElementName == null || childElementName.equals(node.getNodeName())))
{
Element childElement = (Element) node;
return childElement;
}
}
while ((node = node.getNextSibling()) != null);
}
return null;
}
/** Return the first child Element with the given name; if name is null
* returns the first element. */
public static Element firstChildElement(Element element, String childElementName, String attrName, String attrValue)
{
if (element == null)
return null;
// get the first element with the given name
Node node = element.getFirstChild();
if (node != null)
{
do
{
if (node.getNodeType() == Node.ELEMENT_NODE && (childElementName == null || childElementName.equals(node.getNodeName())))
{
Element childElement = (Element) node;
String value = childElement.getAttribute(attrName);
if (value != null && value.equals(attrValue))
{
return childElement;
}
}
}
while ((node = node.getNextSibling()) != null);
}
return null;
}
/** Return the text (node value) contained by the named child node. */
public static String childElementValue(Element element, String childElementName)
{
if (element == null)
return null;
// get the value of the first element with the given name
Element childElement = firstChildElement(element, childElementName);
return elementValue(childElement);
}
/** Return the text (node value) contained by the named child node or a default value if null. */
public static String childElementValue(Element element, String childElementName, String defaultValue)
{
if (element == null)
return defaultValue;
// get the value of the first element with the given name
Element childElement = firstChildElement(element, childElementName);
String elementValue = elementValue(childElement);
if (elementValue == null || elementValue.length() == 0)
return defaultValue;
else
return elementValue;
}
/** Return the text (node value) of the first node under this, works best if normalized. */
public static String elementValue(Element element)
{
if (element == null)
return null;
// make sure we get all the text there...
element.normalize();
Node textNode = element.getFirstChild();
if (textNode == null)
return null;
StringBuffer valueBuffer = new StringBuffer();
do
{
if (textNode.getNodeType() == Node.CDATA_SECTION_NODE || textNode.getNodeType() == Node.TEXT_NODE)
{
valueBuffer.append(textNode.getNodeValue());
}
}
while ((textNode = textNode.getNextSibling()) != null);
return valueBuffer.toString();
}
public static String checkEmpty(String string)
{
if (string != null && string.length() > 0)
return string;
else
return "";
}
public static String checkEmpty(String string1, String string2)
{
if (string1 != null && string1.length() > 0)
return string1;
else
if (string2 != null && string2.length() > 0)
return string2;
else
return "";
}
public static String checkEmpty(String string1, String string2, String string3)
{
if (string1 != null && string1.length() > 0)
return string1;
else
if (string2 != null && string2.length() > 0)
return string2;
else
if (string3 != null && string3.length() > 0)
return string3;
else
return "";
}
public static boolean checkBoolean(String str)
{
return checkBoolean(str, false);
}
public static boolean checkBoolean(String str, boolean defaultValue)
{
if (defaultValue)
{
//default to true, ie anything but false is true
return !"false".equals(str);
}
else
{
//default to false, ie anything but true is false
return "true".equals(str);
}
}
/**
* Local entity resolver to handle J2EE DTDs. With this a http connection
* to sun is not needed during deployment.
* Function boolean hadDTD() is here to avoid validation errors in
* descriptors that do not have a DOCTYPE declaration.
*/
public static class LocalResolver implements EntityResolver
{
private boolean hasDTD = false;
private EntityResolver defaultResolver;
public LocalResolver(EntityResolver defaultResolver)
{
this.defaultResolver = defaultResolver;
}
/**
* Returns DTD inputSource. If DTD was found in the dtds Map and inputSource was created
* flag hasDTD is set to true.
* @param publicId - Public ID of DTD
* @param systemId - System ID of DTD
* @return InputSource of DTD
*/
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException
{
hasDTD = false;
String dtd = UtilProperties.getSplitPropertyValue(UtilURL.fromResource("localdtds.properties"), publicId);
if (Debug.verboseOn())
Debug.logVerbose("[UtilXml.LocalResolver.resolveEntity] resolving DTD with publicId [" + publicId + "], systemId [" + systemId + "] and the dtd file is [" + dtd + "]", module);
if (dtd != null && dtd.length() > 0)
{
try
{
URL dtdURL = UtilURL.fromResource(dtd);
InputStream dtdStream = dtdURL.openStream();
InputSource inputSource = new InputSource(dtdStream);
inputSource.setPublicId(publicId);
hasDTD = true;
if (Debug.verboseOn())
Debug.logVerbose("[UtilXml.LocalResolver.resolveEntity] got LOCAL DTD input source with publicId [" + publicId + "] and the dtd file is [" + dtd + "]", module);
return inputSource;
}
catch (Exception e)
{
Debug.logWarning(e, module);
}
}
if (Debug.verboseOn())
Debug.logVerbose(
"[UtilXml.LocalResolver.resolveEntity] local resolve failed for DTD with publicId [" + publicId + "] and the dtd file is [" + dtd + "], trying defaultResolver",
module);
return defaultResolver.resolveEntity(publicId, systemId);
}
/**
* Returns the boolean value to inform id DTD was found in the XML file or not
* @return boolean - true if DTD was found in XML
*/
public boolean hasDTD()
{
return hasDTD;
}
}
/** Local error handler for entity resolver to DocumentBuilder parser.
* Error is printed to output just if DTD was detected in the XML file.
*/
public static class LocalErrorHandler implements ErrorHandler
{
private String docDescription;
private LocalResolver localResolver;
public LocalErrorHandler(String docDescription, LocalResolver localResolver)
{
this.docDescription = docDescription;
this.localResolver = localResolver;
}
public void error(SAXParseException exception)
{
if (localResolver.hasDTD())
{
Debug.logError("XmlFileLoader: File " + docDescription + " process error. Line: " + String.valueOf(exception.getLineNumber()) + ". Error message: " + exception.getMessage(), module);
}
}
public void fatalError(SAXParseException exception)
{
if (localResolver.hasDTD())
{
Debug.logError(
"XmlFileLoader: File " + docDescription + " process fatal error. Line: " + String.valueOf(exception.getLineNumber()) + ". Error message: " + exception.getMessage(),
module);
}
}
public void warning(SAXParseException exception)
{
if (localResolver.hasDTD())
{
Debug.logError("XmlFileLoader: File " + docDescription + " process warning. Line: " + String.valueOf(exception.getLineNumber()) + ". Error message: " + exception.getMessage(), module);
}
}
}
}
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.crimson.tree.XmlDocument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
/**
* Utilities methods to simplify dealing with JAXP & DOM XML parsing
*
* @author <a href="mailto:jonesde@ofbiz.org">David E. Jones</a>
* @version $Revision: 1.1 $
* @since 2.0
*/
public class UtilXml
{
public static final String module = UtilXml.class.getName();
public static String writeXmlDocument(Document document) throws java.io.IOException
{
if (document == null)
{
Debug.logWarning("[UtilXml.writeXmlDocument] Document was null, doing nothing", module);
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
writeXmlDocument(bos, document);
String outString = bos.toString("UTF-8");
if (bos != null)
bos.close();
return outString;
}
public static void writeXmlDocument(String filename, Document document) throws java.io.FileNotFoundException, java.io.IOException
{
if (document == null)
{
Debug.logWarning("[UtilXml.writeXmlDocument] Document was null, doing nothing", module);
return;
}
if (filename == null)
{
Debug.logWarning("[UtilXml.writeXmlDocument] Filename was null, doing nothing", module);
return;
}
File outFile = new File(filename);
FileOutputStream fos = null;
fos = new FileOutputStream(outFile);
try
{
writeXmlDocument(fos, document);
}
finally
{
if (fos != null)
fos.close();
}
}
public static void writeXmlDocument(OutputStream os, Document document) throws java.io.IOException
{
if (document == null)
{
Debug.logWarning("[UtilXml.writeXmlDocument] Document was null, doing nothing", module);
return;
}
if (os == null)
{
Debug.logWarning("[UtilXml.writeXmlDocument] OutputStream was null, doing nothing", module);
return;
}
//todo:xml序列化需要改进
// if(document instanceof XmlDocument) {
//Crimson writer
XmlDocument xdoc = (XmlDocument) document;
xdoc.write(os);
// }
// else {
// // Xerces writer
// OutputFormat format = new OutputFormat(document);
// format.setIndent(2);
//
// XMLSerializer serializer = new XMLSerializer(os, format);
// serializer.asDOMSerializer();
// serializer.serialize(document.getDocumentElement());
// }
}
public static Document readXmlDocument(String content) throws SAXException, ParserConfigurationException, java.io.IOException
{
return readXmlDocument(content, true);
}
public static Document readXmlDocument(String content,String charSet) throws SAXException, ParserConfigurationException, java.io.IOException
{
return readXmlDocument(content, true,charSet);
}
public static Document readXmlDocument(String content, boolean validate) throws SAXException, ParserConfigurationException, java.io.IOException
{
if (content == null)
{
Debug.logWarning("[UtilXml.readXmlDocument] content was null, doing nothing", module);
return null;
}
ByteArrayInputStream bis = new ByteArrayInputStream(content.getBytes("UTF-8"));
return readXmlDocument(bis, validate, "Internal Content");
}
public static Document readXmlDocument(String content, boolean validate,String charSet) throws SAXException, ParserConfigurationException, java.io.IOException
{
if (content == null)
{
Debug.logWarning("[UtilXml.readXmlDocument] content was null, doing nothing", module);
return null;
}
ByteArrayInputStream bis = new ByteArrayInputStream(content.getBytes(charSet));
return readXmlDocument(bis, validate, "Internal Content");
}
public static Document readXmlDocument(URL url) throws SAXException, ParserConfigurationException, java.io.IOException
{
return readXmlDocument(url, true);
}
public static Document readXmlDocument(URL url, boolean validate) throws SAXException, ParserConfigurationException, java.io.IOException
{
if (url == null)
{
Debug.logWarning("[UtilXml.readXmlDocument] URL was null, doing nothing", module);
return null;
}
// System.out.println(url);
return readXmlDocument(url.openStream(), validate, url.toString());
}
public static Document readXmlDocument(InputStream is) throws SAXException, ParserConfigurationException, java.io.IOException
{
return readXmlDocument(is, true, null);
}
public static Document readXmlDocument(InputStream is, boolean validate, String docDescription) throws SAXException, ParserConfigurationException, java.io.IOException
{
if (is == null)
{
Debug.logWarning("[UtilXml.readXmlDocument] InputStream was null, doing nothing", module);
return null;
}
Document document = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(validate);
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
if (validate)
{
LocalResolver lr = new LocalResolver(new DefaultHandler());
ErrorHandler eh = new LocalErrorHandler(docDescription, lr);
builder.setEntityResolver(lr);
builder.setErrorHandler(eh);
}
document = builder.parse(is);
return document;
}
public static Document makeEmptyXmlDocument()
{
return makeEmptyXmlDocument(null);
}
public static Document makeEmptyXmlDocument(String rootElementName)
{
Document document = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
// factory.setNamespaceAware(true);
try
{
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.newDocument();
}
catch (Exception e)
{
Debug.logError(e, module);
}
if (document == null)
return null;
if (rootElementName != null)
{
Element rootElement = document.createElement(rootElementName);
document.appendChild(rootElement);
}
return document;
}
/** Creates a child element with the given name and appends it to the element child node list. */
public static Element addChildElement(Element element, String childElementName, Document document)
{
Element newElement = document.createElement(childElementName);
element.appendChild(newElement);
return newElement;
}
/** Creates a child element with the given name and appends it to the element child node list.
* Also creates a Text node with the given value and appends it to the new elements child node list.
*/
public static Element addChildElementValue(Element element, String childElementName, String childElementValue, Document document)
{
Element newElement = addChildElement(element, childElementName, document);
newElement.appendChild(document.createTextNode(childElementValue));
return newElement;
}
/** Creates a child element with the given name and appends it to the element child node list.
* Also creates a CDATASection node with the given value and appends it to the new elements child node list.
*/
public static Element addChildElementCDATAValue(Element element, String childElementName, String childElementValue, Document document)
{
Element newElement = addChildElement(element, childElementName, document);
newElement.appendChild(document.createCDATASection(childElementValue));
return newElement;
}
/** Return a List of Element objects that have the given name and are
* immediate children of the given element; if name is null, all child
* elements will be included. */
public static List childElementList(Element element, String childElementName)
{
if (element == null)
return null;
List elements = new LinkedList();
Node node = element.getFirstChild();
if (node != null)
{
do
{
if (node.getNodeType() == Node.ELEMENT_NODE && (childElementName == null || childElementName.equals(node.getNodeName())))
{
Element childElement = (Element) node;
elements.add(childElement);
}
}
while ((node = node.getNextSibling()) != null);
}
return elements;
}
/** Return the first child Element with the given name; if name is null
* returns the first element. */
public static Element firstChildElement(Element element, String childElementName)
{
if (element == null)
return null;
// get the first element with the given name
Node node = element.getFirstChild();
if (node != null)
{
do
{
if (node.getNodeType() == Node.ELEMENT_NODE && (childElementName == null || childElementName.equals(node.getNodeName())))
{
Element childElement = (Element) node;
return childElement;
}
}
while ((node = node.getNextSibling()) != null);
}
return null;
}
/** Return the first child Element with the given name; if name is null
* returns the first element. */
public static Element firstChildElement(Element element, String childElementName, String attrName, String attrValue)
{
if (element == null)
return null;
// get the first element with the given name
Node node = element.getFirstChild();
if (node != null)
{
do
{
if (node.getNodeType() == Node.ELEMENT_NODE && (childElementName == null || childElementName.equals(node.getNodeName())))
{
Element childElement = (Element) node;
String value = childElement.getAttribute(attrName);
if (value != null && value.equals(attrValue))
{
return childElement;
}
}
}
while ((node = node.getNextSibling()) != null);
}
return null;
}
/** Return the text (node value) contained by the named child node. */
public static String childElementValue(Element element, String childElementName)
{
if (element == null)
return null;
// get the value of the first element with the given name
Element childElement = firstChildElement(element, childElementName);
return elementValue(childElement);
}
/** Return the text (node value) contained by the named child node or a default value if null. */
public static String childElementValue(Element element, String childElementName, String defaultValue)
{
if (element == null)
return defaultValue;
// get the value of the first element with the given name
Element childElement = firstChildElement(element, childElementName);
String elementValue = elementValue(childElement);
if (elementValue == null || elementValue.length() == 0)
return defaultValue;
else
return elementValue;
}
/** Return the text (node value) of the first node under this, works best if normalized. */
public static String elementValue(Element element)
{
if (element == null)
return null;
// make sure we get all the text there...
element.normalize();
Node textNode = element.getFirstChild();
if (textNode == null)
return null;
StringBuffer valueBuffer = new StringBuffer();
do
{
if (textNode.getNodeType() == Node.CDATA_SECTION_NODE || textNode.getNodeType() == Node.TEXT_NODE)
{
valueBuffer.append(textNode.getNodeValue());
}
}
while ((textNode = textNode.getNextSibling()) != null);
return valueBuffer.toString();
}
public static String checkEmpty(String string)
{
if (string != null && string.length() > 0)
return string;
else
return "";
}
public static String checkEmpty(String string1, String string2)
{
if (string1 != null && string1.length() > 0)
return string1;
else
if (string2 != null && string2.length() > 0)
return string2;
else
return "";
}
public static String checkEmpty(String string1, String string2, String string3)
{
if (string1 != null && string1.length() > 0)
return string1;
else
if (string2 != null && string2.length() > 0)
return string2;
else
if (string3 != null && string3.length() > 0)
return string3;
else
return "";
}
public static boolean checkBoolean(String str)
{
return checkBoolean(str, false);
}
public static boolean checkBoolean(String str, boolean defaultValue)
{
if (defaultValue)
{
//default to true, ie anything but false is true
return !"false".equals(str);
}
else
{
//default to false, ie anything but true is false
return "true".equals(str);
}
}
/**
* Local entity resolver to handle J2EE DTDs. With this a http connection
* to sun is not needed during deployment.
* Function boolean hadDTD() is here to avoid validation errors in
* descriptors that do not have a DOCTYPE declaration.
*/
public static class LocalResolver implements EntityResolver
{
private boolean hasDTD = false;
private EntityResolver defaultResolver;
public LocalResolver(EntityResolver defaultResolver)
{
this.defaultResolver = defaultResolver;
}
/**
* Returns DTD inputSource. If DTD was found in the dtds Map and inputSource was created
* flag hasDTD is set to true.
* @param publicId - Public ID of DTD
* @param systemId - System ID of DTD
* @return InputSource of DTD
*/
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException
{
hasDTD = false;
String dtd = UtilProperties.getSplitPropertyValue(UtilURL.fromResource("localdtds.properties"), publicId);
if (Debug.verboseOn())
Debug.logVerbose("[UtilXml.LocalResolver.resolveEntity] resolving DTD with publicId [" + publicId + "], systemId [" + systemId + "] and the dtd file is [" + dtd + "]", module);
if (dtd != null && dtd.length() > 0)
{
try
{
URL dtdURL = UtilURL.fromResource(dtd);
InputStream dtdStream = dtdURL.openStream();
InputSource inputSource = new InputSource(dtdStream);
inputSource.setPublicId(publicId);
hasDTD = true;
if (Debug.verboseOn())
Debug.logVerbose("[UtilXml.LocalResolver.resolveEntity] got LOCAL DTD input source with publicId [" + publicId + "] and the dtd file is [" + dtd + "]", module);
return inputSource;
}
catch (Exception e)
{
Debug.logWarning(e, module);
}
}
if (Debug.verboseOn())
Debug.logVerbose(
"[UtilXml.LocalResolver.resolveEntity] local resolve failed for DTD with publicId [" + publicId + "] and the dtd file is [" + dtd + "], trying defaultResolver",
module);
return defaultResolver.resolveEntity(publicId, systemId);
}
/**
* Returns the boolean value to inform id DTD was found in the XML file or not
* @return boolean - true if DTD was found in XML
*/
public boolean hasDTD()
{
return hasDTD;
}
}
/** Local error handler for entity resolver to DocumentBuilder parser.
* Error is printed to output just if DTD was detected in the XML file.
*/
public static class LocalErrorHandler implements ErrorHandler
{
private String docDescription;
private LocalResolver localResolver;
public LocalErrorHandler(String docDescription, LocalResolver localResolver)
{
this.docDescription = docDescription;
this.localResolver = localResolver;
}
public void error(SAXParseException exception)
{
if (localResolver.hasDTD())
{
Debug.logError("XmlFileLoader: File " + docDescription + " process error. Line: " + String.valueOf(exception.getLineNumber()) + ". Error message: " + exception.getMessage(), module);
}
}
public void fatalError(SAXParseException exception)
{
if (localResolver.hasDTD())
{
Debug.logError(
"XmlFileLoader: File " + docDescription + " process fatal error. Line: " + String.valueOf(exception.getLineNumber()) + ". Error message: " + exception.getMessage(),
module);
}
}
public void warning(SAXParseException exception)
{
if (localResolver.hasDTD())
{
Debug.logError("XmlFileLoader: File " + docDescription + " process warning. Line: " + String.valueOf(exception.getLineNumber()) + ". Error message: " + exception.getMessage(), module);
}
}
}
}
发表评论
-
java输出文件
2010-12-01 16:51 1347try { File file = new Fil ... -
Java字符串将不是字符数字的字符转换为十六进制字符
2010-07-12 10:28 1323char data[] = "asdfasdf中国1 ... -
Java解压ZIP文件同时解决压缩文件中含有中文名文件乱码的问题
2010-04-22 13:12 5328在使用Java对ZIP压缩文件进行解压的方式中有两种,一种是使 ... -
Java进行WebService通讯
2008-05-19 15:10 2165package com.yc.ycportal.cqkf.se ... -
Java实现MD5算法加密
2008-05-16 09:17 1205/** * MD5 算法的Java Bean */ pac ... -
Java手工打Jar包
2008-05-10 11:28 1878用法:jar {ctxu}[vfm0Mi] [jar-文件] ... -
Java解压缩ZIP文件同时包含Jar包解决ZIP包中含有中文名称信息的文件
2008-05-07 13:42 3309我们知道压缩文件中有第一个文件夹为原始文件夹:例如我们对一个目 ... -
Java上传文件实例
2008-05-05 10:08 4001package com.yc.eap.util; impor ... -
Servlet中文API文档
2008-04-26 15:47 2202基本类和接口 一、javax.servlet.Servlet ... -
ServletConfig和ServletConfig参数访问
2008-04-26 14:20 1342HttpServletRequest,HttpServletR ... -
Java上传文件同时含有表单域的实现
2008-04-25 17:08 2104package com.yc.eap.util; impor ... -
Jsp通过文件流实现文件下载
2008-04-23 10:44 2867<%@ page contentType="a ... -
Commons-fileupload工具的API与开发实例解析(三)
2008-04-23 10:25 19011.3.3 MultipartStream类 Multipar ... -
Commons-fileupload工具的API与开发实例解析(二)
2008-04-23 10:24 21551.2.5 文件上传编程实例 下面参考图1.2中看到的示例代码 ... -
Commons-fileupload工具的API与开发实例解析(一)
2008-04-23 10:22 3483文件上传组件的应用与编写 在许多Web站点应用中都需要为 ... -
Java解析XML文件
2008-04-23 10:15 1762package com.yc.ycportal.ge.util ... -
Java压缩与解压缩文件
2008-04-23 10:05 1711package com.yc.ycportal.ge.util ... -
Java只获取系统时间的年份
2008-04-23 10:04 5568public static String getYear(){ ... -
Java连接Oracle数据库调用存储过程获取数据集
2008-04-23 10:03 2357package com.yc.ycportal.ge.util ... -
Java实现Ftp文件下载
2008-04-23 10:02 4586从http://www.enterprisedt.com/下载 ...
相关推荐
### Java解析XML字符串 在给定的代码示例中,我们看到了如何使用JDOM库来解析一个XML字符串,并对其进行操作。下面我们将详细解析这个过程: 1. **初始化XML源**:首先,将XML字符串转化为`StringReader`对象,这...
要将这样的XML字符串转换为List,我们需要解析XML并将其转化为相应的Java或C#对象。这个过程通常分为以下几个步骤: 1. **解析XML**:可以使用内置库或第三方库来解析XML字符串。在Java中,可以使用DOM(Document ...
2. 使用`parse()`方法解析XML字符串为`Document`对象。 3. 遍历和操作`Document`对象,获取XML数据。 对于初学者来说,理解并熟练掌握这些步骤至关重要,因为XML解析是Java开发中常见的需求,尤其在数据交换和配置...
- **解析XML字符串**:使用`DocumentHelper.parseText`方法直接解析XML字符串,返回一个`Document`对象。 接下来的操作与使用`SAXReader`的方式类似,都是通过`Document`对象获取根元素、迭代子元素并提取所需的...
在Java中,将Java对象的数据封装成XML格式的字符串,通常涉及到对象序列化的过程。对象序列化是将对象的状态转换为字节流,以便存储或在网络上传输。这个过程可以通过实现`java.io.Serializable`接口来完成。反序列...
最后,将格式化后的XML字符串返回,供后续使用。在`XmlFormatUtils`类中,这个过程可能封装在一个静态方法里,如`formatXmlFile(String xmlFilePath)`,并返回`formattedXmlString`。 通过上述步骤,我们能够实现...
Java XML解析是处理XML文档的重要技术,XML(Extensible Markup Language)作为一种通用的数据交换格式,广泛应用于各种领域。本主题将深入探讨Java中常用的两种XML解析库:DOM4J和JDOM。 首先,我们来看DOM4J。DOM...
将读取到的XML字符串转换为`InputSource`对象,然后用`DocumentBuilder`解析这个源。 ```java InputSource inputSource = new InputSource(new StringReader(xmlContent.toString())); Document document = ...
同时,我们还会讨论如何使用jQuery在前端解析XML并展示数据。 首先,让我们了解XML的基本结构。XML文档由元素(Element)、属性(Attribute)、文本内容(Text Content)等组成。元素是XML的核心,它们通过层级关系...
`xmlToMap`方法首先使用SAXReader解析XML字符串,然后递归地遍历XML文档的元素,将它们转换为Map结构。 `mapToXml`方法则将Map转换成XML字符串: ```java import org.dom4j.Document; import org.dom4j....
本篇文章将详细介绍Java解析XML的四种方法以及JSON格式的相关知识。 一、DOM解析 DOM(Document Object Model)是W3C推荐的一种解析XML的标准方法,它将整个XML文档加载到内存中,形成一个树形结构,便于遍历和操作...
当我们需要将XML字符串解析并映射到Java Bean对象时,dom4j是一个常用的库。本篇文章将详细探讨如何使用dom4j库实现这个过程。 首先,dom4j是一个强大的Java XML API,它提供了丰富的功能,如读取、写入、修改和...
本项目主要关注如何在Java中生成指定格式的XML字符串以及如何解析XML字符串得到对应的Map格式内容。 首先,让我们详细探讨Java生成XML的过程。在Java中,我们可以使用DOM(文档对象模型)、SAX(简单API for XML)...
这些文件通常包含了处理XML数据的相关工具方法,可能包括读取XML文件、解析XML字符串、格式化XML以及生成新的XML文件等操作。 `XMLFileUtil.java`可能包含了一些与XML文件I/O相关的功能,比如读取XML文件到字符串,...
最后,使用`Transformer`将`Document`转换为XML字符串或写入文件。 每个实例都需要理解文件结构,正确处理数据类型,并确保文件操作的异常处理。在实际应用中,可能还需要对性能进行优化,如使用内存流处理大文件,...
首先,你需要创建一个`JAXBContext`实例,然后使用`Marshaller`对象将`Map`对象写入XML字符串。 ```java import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; public String mapToXml(Map, ...
本文将深入探讨Java平台下解析XML的四种主流方法:DOM、SAX、DOM4J和JDOM。 1. **DOM(Document Object Model)解析XML** DOM是一种树形结构,它将整个XML文档加载到内存中,形成一个完整的对象模型。这种解析方式...
首先创建一个DocumentBuilderFactory实例,然后通过它获取DocumentBuilder,再用DocumentBuilder解析XML文件得到Document对象。接着,可以遍历Document对象的节点,执行读写操作。 - 对于SAX解析,我们需要实现org....
一、Java解析XML 1. DOM解析:Document Object Model(DOM)是XML文档的一种树形表示方式。Java中的`javax.xml.parsers.DocumentBuilderFactory`和`org.w3c.dom.Document`类用于构建DOM模型。首先,创建`...
在本场景中,我们将探讨如何通过WebService来调用数据库中的数据并以XML格式进行返回。 1. **XML基础**:XML全称为Extensible Markup Language,它是一种自定义标记语言,用于结构化地表示数据。XML文档由元素、...