- 浏览: 131614 次
- 性别:
- 来自: 上海
文章分类
最新评论
-
qq466862016:
不错的文章
JDK动态代理与CGLIB代理的对比 -
jinxiongyi:
你好,jpedal pdf转换图片的 画质,怎么提高。。我转 ...
介绍几款PDF转图片的开源工具 -
qqdwll:
转图片消耗的内存还是不小。 有时间得找找有没有更好的办法, 把 ...
介绍几款PDF转图片的开源工具 -
xiaoyao3857:
Thanks for your work!It's help ...
Keeping Eclipse running clean (转载) -
iceside:
图片讲解非常详细,说清了引用复制是怎么回事
Java 值传递的终极解释
XML 处理实践
一: DOM解析
1. 把XML文挡以String读出
File docFile = new File( fileName);
//FileUtils. commons-io-1.4.jar
String result = FileUtils.readFileToString(new File(fileName), UTF_8);
2. 把String写出到XML文挡
File dest = new File (fileName);
String contens = contents;
FileUtils.writeStringToFile(dest, contents, UTF_8);
3. String to org.w3c.dom.Document
//DocumentBuilderFactory. xml-apis.jar
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
String nodeData = xml content;
Document result = builder.parse(new InputSource(new StringReader(nodeData)));
4. String to org.apache.xerces.dom.DocumentImpl
//DocumentImpl. xercesImpl.jar
DocumentImpl result = null;
//DOMParser. xercesImpl.jar
DOMParser parser = new DOMParser();
//xml-apis.jar
DefaultHandler defaultHandler = new DefaultHandler();
parser.setErrorHandler(defaultHandler);
InputSource is = new InputSource(new StringReader(nodeData));
parser.parse(is);
result = (DocumentImpl) parser.getDocument();
5. 通过父节点, 返回一个 (所有)的子节点
/**Given any parent element and the tag name of a child element, this returns
the first child element. If there is multiple child elements, this method
only retrieves the first. It will also create a child element if it does
not exist and add it to the parent element if the <code>addChildIfNotPresent</code>
flag is set to true.
*/
public static Element findChildForParent(Element parentElement, String childTagName, boolean addChildIfNotPresent) {
Element childElement = null;
if (parentElement != null) {
NodeList list = parentElement.getElementsByTagName(childTagName);
if (list != null && list.getLength() > 0) {
childElement = (Element)list.item(0);
} else {
if (addChildIfNotPresent) {
childElement = addElement(parentElement, childTagName);
}
}
}
return childElement;
}
public static Element addElement(Element parentElement, String childTagName, String value) {
Element childElement = null;
if (parentElement != null) {
childElement = parentElement.getOwnerDocument().createElement(childTagName);
parentElement.appendChild(childElement);
if (value != null) {
Node text = parentElement.getOwnerDocument().createTextNode(value);
childElement.appendChild(text);
}
}
return childElement;
}
6。 取得text文本的一些方法
a. //xmi-apis.jar
/**
* Get the text of an Element
*
*@param textElement the Element to retrieve the text from
*@return the text of the Element
*/
public static String textForElement(Element textElement) {
String value = null;
if (textElement != null) {
Node child = textElement.getFirstChild();
while (child != null) {
if ((child.getNodeType() == Node.TEXT_NODE) || (child.getNodeType() == Node.CDATA_SECTION_NODE)) {
value = child.getNodeValue();
child = null;
} else {
child = child.getNextSibling();
}
}
}
return value;
}
b. // CachedXPathAPI come from xalan.jar
//org.w3c.dom.Node implement in xml-apis.jar
/**
* Description of the Method
*
*@param xpathToElement Description of the Parameter
*@param cachedXpath Description of the Parameter
*@param node Description of the Parameter
*@return Description of the Return Value
*@exception CVXMLException Description of the Exception
*/
public static String textForElement(String xpathToElement, Node node, org.apache.xpath.CachedXPathAPI cachedXpath) throws CVXMLException {
String results = null;
if (cachedXpath != null) {
try {
if (logger.isDebugEnabled()) logger.debug("getting textForElement using cachedxpath and xpath : " + cachedXpath + " -- " + xpathToElement);
Node n = cachedXpath.selectSingleNode(node, xpathToElement);
if (n != null) {
results = textForElement((Element)n);
}
} catch (Throwable t) {
if (logger.isDebugEnabled()) logger.debug("Error getting textForElement", t);
//throw new CVXMLException(t);
}
} else {
results = textForElement(xpathToElement, node);
}
return results;
}
c. Using xpath get the text from Document.
//XPathAPI. xalan.jar
/**
* Description of the Method
*
*@param xpathToElement Description of the Parameter
*@param doc Description of the Parameter
*@return Description of the Return Value
*@exception CVXMLException Description of the Exception
*/
public static String textForElement(String xpathToElement, Document doc) throws CVXMLException {
String results = null;
try {
if (logger.isDebugEnabled()) logger.debug("getting textForElement using old way -- no cachedxpathapi");
Node n = XPathAPI.selectSingleNode(doc.getDocumentElement(), xpathExpression);
if (n != null) {
results = textForElement((Element)n);
}
} catch (CVXMLException e) {
e.appendLogInfo("Unable to find a node using the xpath : " + xpathToElement);
throw e;
} catch (Throwable t) {
if (logger.isDebugEnabled()) logger.debug("Error getting textForElement", t);
}
return results;
}
7. 取得Attibute的方法
//xml-apis.jar
public static String textForAttribute(Element parentElement, String attributeName) {
String attributeText = null;
Attr classAttribute = parentElement.getAttributeNode(attributeName);
if (classAttribute != null) {
attributeText = classAttribute.getValue();
}
return attributeText;
}
8. 设置text和attribute的方法
//xml-apis.jar
public static void setTextForElement(Element textElement, String textToBeUsed) {
if (textToBeUsed != null) {
if (textToBeUsed.length() > 0){
textToBeUsed = StringUtils.removeIncompatibilityCharacters(textToBeUsed);
}
if (textElement.hasChildNodes()) {
// search for a text or cdata node to set the value of
boolean found = false;
boolean done = false;
Node child = textElement.getFirstChild();
while (!found && !done) {
if (child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE) {
done = true;
found = true;
} else {
child = child.getNextSibling();
if (child == null) {
done = true;
}
}
}
if (found) {
child.setNodeValue(textToBeUsed);
} else {
//Node text = textElement.getOwnerDocument().createTextNode(textToBeUsed);//GR 04/01/2004 -- Changed to create CData Section instead
Node text = textElement.getOwnerDocument().createCDATASection(textToBeUsed);
textElement.appendChild(text);
}
}
else {
// no text nodes found to set a value for, so must create one
//textElement.appendChild(textElement.getOwnerDocument().createTextNode(textToBeUsed));//GR 04/01/2004 -- Changed to create CData Section instead
textElement.appendChild(textElement.getOwnerDocument().createCDATASection(textToBeUsed));
}
}
}
public static String removeIncompatibilityCharacters(String textStr) {
CharArrayWriter charArrayWriter = new CharArrayWriter();
for (int i = 0; i < textStr.length(); i++) {
if (Character.isDefined(textStr.charAt(i))) {
int charVal = (int) textStr.charAt(i);
// Control Characters --> NUL, SOH, STX, ETX, EOT, ENQ, ACK, BEL, BS
if (charVal >= 0x00 && charVal <= 0x08) {
continue;
}
// Control Characters --> CR, SO, SI, DLE, DC1, DC2, DC3, DC4, NAK, SYN, ETB, CAN, EM, SUB, ESC, FS, GS, RS, US
if (charVal >= 0x0B && charVal <= 0x1F) {
continue;
}
// The remaining characters are defined at http://www.w3.org/TR/2006/REC-xml-20060816/#charsets
if (charVal >= 0x7F && charVal <= 0x84) {
continue;
}
if (charVal >= 0x86 && charVal <= 0x9F) {
continue;
}
if (charVal >= 0xFDD0 && charVal <= 0xFDDF) {
continue;
}
if (charVal >= 0x1FFFE && charVal <= 0x1FFFF) {
continue;
}
if (charVal >= 0x2FFFE && charVal <= 0x2FFFF) {
continue;
}
if (charVal >= 0x3FFFE && charVal <= 0x3FFFF) {
continue;
}
if (charVal >= 0x4FFFE && charVal <= 0x4FFFF) {
continue;
}
if (charVal >= 0x5FFFE && charVal <= 0x5FFFF) {
continue;
}
if (charVal >= 0x6FFFE && charVal <= 0x6FFFF) {
continue;
}
if (charVal >= 0x7FFFE && charVal <= 0x7FFFF) {
continue;
}
if (charVal >= 0x8FFFE && charVal <= 0x8FFFF) {
continue;
}
if (charVal >= 0x9FFFE && charVal <= 0x9FFFF) {
continue;
}
if (charVal >= 0xAFFFE && charVal <= 0xAFFFF) {
continue;
}
if (charVal >= 0xBFFFE && charVal <= 0xBFFFF) {
continue;
}
if (charVal >= 0xCFFFE && charVal <= 0xCFFFF) {
continue;
}
if (charVal >= 0xDFFFE && charVal <= 0xDFFFF) {
continue;
}
if (charVal >= 0xEFFFE && charVal <= 0xEFFFF) {
continue;
}
if (charVal >= 0xFFFFE && charVal <= 0xFFFFF) {
continue;
}
if (charVal >= 0x10FFFE && charVal <= 0x10FFFF) {
continue;
}
charArrayWriter.write(charVal);
}
}
return new String(charArrayWriter.toCharArray());
}
public static void setTextForAttribute(Element parentElement, String attributeName, String attributeValue) {
parentElement.setAttribute(attributeName, attributeValue);
}
9. 创建Document
a. //xml-apis.jar
//Creates a new document object with the root node having the name: <code>rootElementName</code>\
public static Document createDocumentWithRoot(String rootElementName, boolean x) {
Document newRecordDoc = null;
if (rootElementName != null && !rootElementName.trim().equals("")) {
newRecordDoc = createDocument(true);
// Once the new document has been created, add the necessary root element
newRecordDoc.appendChild(newRecordDoc.createElement(rootElementName));
}
return newRecordDoc;
}
b. //Creates a new document object without the root node being set on the
public static Document createDocument(boolean x) {
Document newRecordDoc = null;
try {
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
newRecordDoc = docBuilder.newDocument();
} catch (Exception e) {
ExceptionLogWriter.logException(e, "DOMHelper.createDocument(). Problem instantiating a new DocumentBuilder");
}
return newRecordDoc;
}
10. 替换节点
a. //xml-apis.jar
public static Document replaceRootNodeName(String xml, String newValue) throws CVXMLException {
Document doc = stringToDocument(xml, true);
replaceRootNodeName(doc, newValue);
return doc;
}
b.
public static void replaceRootNodeName(Document doc, String newValue) {
replaceNodeName(doc, doc.getDocumentElement(), newValue);
}
c.
public static void replaceNodeName(Document doc, Element element, String newValue) {
//Create an element with the new name
Element element = doc.createElement(newValue);
// Copy the attributes to the new element
NamedNodeMap attrs = element.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
Attr attr2 = (Attr)doc.importNode(attrs.item(i), true);
element2.getAttributes().setNamedItem(attr2);
}
// Move all the children
while (element.hasChildNodes()) {
element2.appendChild(element.getFirstChild());
}
// Replace the old node with the new node
element.getParentNode().replaceChild(element2, element);
}
二. SAX 解析
class XMLDocument extends DefaultHandler {
Document doc;
String elementName = "";
String attribName = "";
String attribVal = "";
boolean addAttr = false;
Element currElement;
Element root;
String rootName;
boolean hasDocument = false;
boolean hasRoot = false;
int count = 0;
/** Constructor for the XMLDocument object */
XMLDocument() {
super();
hasDocument = false;
}
/**
*@param val Document
*/
XMLDocument(Document val) {
super();
doc = val;
hasDocument = true;
}
/**
* Method to set the Root
*
*@param val The new root value
*/
public void setRoot(String val) {
rootName = val;
hasRoot = true;
}
/**
* Method to add an attribute.
*
*@param element String containing the elementName
*@param attribute String containing the attribute name
*@param value String containing the attribute value
*/
public void addAttribute(String element, String attribute, String value) {
elementName = element;
attribName = attribute;
attribVal = value;
addAttr = true;
}
/**
*@exception SAXException If the root element name is missing
*/
public void startDocument() throws SAXException {
if (!hasDocument) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
doc = parser.newDocument();
} catch (Exception e) {
throw new SAXException(e);
}
if (rootName == null || rootName.equals("")) {
throw new SAXException("Missing root element name, call setRoot() first");
}
}
if (hasRoot) {
root = (Element)doc.createElement(rootName);
doc.appendChild(root);
}
}
/**
*@param uri String containing the uri
*@param localName String containing the localName
*@param rawName String containing the rawName
*@param atts Attributes
*@exception SAXException Description of the Exception
*/
public void startElement(String uri, String localName, String rawName, Attributes atts) throws SAXException {
// Assume the first element encountered is the root element
// Check the element to see if it is one we are interested in processing
if (hasRoot) {
if (!rawName.equalsIgnoreCase(rootName)) {
currElement = (Element)doc.createElement(rawName);
for (int i = 0; i < atts.getLength(); i++) {
currElement.setAttribute(atts.getQName(i), atts.getValue(i));
}
if (rawName.equals(elementName) && addAttr) {
// Add the new attribute if specified
currElement.setAttribute(attribName, attribVal);
}
root.appendChild(currElement);
} else {
currElement = (Element)doc.createElement(rawName);
for (int i = 0; i < atts.getLength(); i++) {
currElement.setAttribute(atts.getQName(i), atts.getValue(i));
}
}
} else {
// Create a new element - used for stringToDoc(String) method
if (count == 0) {
root = (Element)doc.createElement(rawName);
doc.appendChild(root);
}
currElement = (Element)doc.createElement(rawName);
for (int i = 0; i < atts.getLength(); i++) {
currElement.setAttribute(atts.getQName(i), atts.getValue(i));
}
root.appendChild(currElement);
count++;
}
}
/**
*@param ch Description of the Parameter
*@param start Description of the Parameter
*@param length Description of the Parameter
*@exception SAXException Description of the Exception
*/
public void characters(char[] ch, int start, int length) throws SAXException {
Text text = doc.createTextNode(new String(ch, start, length));
if (currElement != null) {
currElement.appendChild(text);
}
}
/**
* Description of the Method
*
*@return Description of the Return Value
*/
public Document document() {
return doc;
}
}
//xml-apis.jar
public Object process( InputSource is ) {
protected List tags = new ArrayList(0);
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating( strict );
SAXParser sp = spf.newSAXParser();
XMLReader xmlReader = sp.getXMLReader();
xmlReader.setContentHandler( this );
xmlReader.setErrorHandler( this );
if( entityResolver != null ) {
xmlReader.setEntityResolver( entityResolver );
}
xmlReader.parse( is );
if( tags.size() == 0 ) return finish( null );
return finish( tags.remove(0) );
}
MyProcess processor = new ProcessImpl(conf, rc);
//XMLBuilder extends XMLDocument 策略模式
XMLBuilder xb = new XMLBuilder(processor);
xb.process(new StringReader( ""));
三. xsl parse xml
//xml-apis.jar
protected void transformXml(String path, String documentXml) {
StreamSource xsl = new StreamSource(new File(xslFileName));
StringReader reader = new StringReader(documentXml);
StreamSource xml = new StreamSource(reader);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
Transformer transformer = null;
try {
transformer = TransformerFactory.newInstance().newTransformer(xsl);
}
try {
if(null != transformer) {
transformer.transform(xml, result);
}
}
xsl:
<root>
<xsl:template match="/book">
<xsl:if test="date/text()" >
<newnode><xsl:value-of select="date"/></facet>
</xsl:if>
<xsl:apply-templates select="Auther/lan"/>
</root>
<xsl:template match="Auther/lan">
<xsl:if test="position()=1">
<p><xsl:value-of select="key"/></p>
</xsl:if>
</xsl:template>
一: DOM解析
1. 把XML文挡以String读出
File docFile = new File( fileName);
//FileUtils. commons-io-1.4.jar
String result = FileUtils.readFileToString(new File(fileName), UTF_8);
2. 把String写出到XML文挡
File dest = new File (fileName);
String contens = contents;
FileUtils.writeStringToFile(dest, contents, UTF_8);
3. String to org.w3c.dom.Document
//DocumentBuilderFactory. xml-apis.jar
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
String nodeData = xml content;
Document result = builder.parse(new InputSource(new StringReader(nodeData)));
4. String to org.apache.xerces.dom.DocumentImpl
//DocumentImpl. xercesImpl.jar
DocumentImpl result = null;
//DOMParser. xercesImpl.jar
DOMParser parser = new DOMParser();
//xml-apis.jar
DefaultHandler defaultHandler = new DefaultHandler();
parser.setErrorHandler(defaultHandler);
InputSource is = new InputSource(new StringReader(nodeData));
parser.parse(is);
result = (DocumentImpl) parser.getDocument();
5. 通过父节点, 返回一个 (所有)的子节点
/**Given any parent element and the tag name of a child element, this returns
the first child element. If there is multiple child elements, this method
only retrieves the first. It will also create a child element if it does
not exist and add it to the parent element if the <code>addChildIfNotPresent</code>
flag is set to true.
*/
public static Element findChildForParent(Element parentElement, String childTagName, boolean addChildIfNotPresent) {
Element childElement = null;
if (parentElement != null) {
NodeList list = parentElement.getElementsByTagName(childTagName);
if (list != null && list.getLength() > 0) {
childElement = (Element)list.item(0);
} else {
if (addChildIfNotPresent) {
childElement = addElement(parentElement, childTagName);
}
}
}
return childElement;
}
public static Element addElement(Element parentElement, String childTagName, String value) {
Element childElement = null;
if (parentElement != null) {
childElement = parentElement.getOwnerDocument().createElement(childTagName);
parentElement.appendChild(childElement);
if (value != null) {
Node text = parentElement.getOwnerDocument().createTextNode(value);
childElement.appendChild(text);
}
}
return childElement;
}
6。 取得text文本的一些方法
a. //xmi-apis.jar
/**
* Get the text of an Element
*
*@param textElement the Element to retrieve the text from
*@return the text of the Element
*/
public static String textForElement(Element textElement) {
String value = null;
if (textElement != null) {
Node child = textElement.getFirstChild();
while (child != null) {
if ((child.getNodeType() == Node.TEXT_NODE) || (child.getNodeType() == Node.CDATA_SECTION_NODE)) {
value = child.getNodeValue();
child = null;
} else {
child = child.getNextSibling();
}
}
}
return value;
}
b. // CachedXPathAPI come from xalan.jar
//org.w3c.dom.Node implement in xml-apis.jar
/**
* Description of the Method
*
*@param xpathToElement Description of the Parameter
*@param cachedXpath Description of the Parameter
*@param node Description of the Parameter
*@return Description of the Return Value
*@exception CVXMLException Description of the Exception
*/
public static String textForElement(String xpathToElement, Node node, org.apache.xpath.CachedXPathAPI cachedXpath) throws CVXMLException {
String results = null;
if (cachedXpath != null) {
try {
if (logger.isDebugEnabled()) logger.debug("getting textForElement using cachedxpath and xpath : " + cachedXpath + " -- " + xpathToElement);
Node n = cachedXpath.selectSingleNode(node, xpathToElement);
if (n != null) {
results = textForElement((Element)n);
}
} catch (Throwable t) {
if (logger.isDebugEnabled()) logger.debug("Error getting textForElement", t);
//throw new CVXMLException(t);
}
} else {
results = textForElement(xpathToElement, node);
}
return results;
}
c. Using xpath get the text from Document.
//XPathAPI. xalan.jar
/**
* Description of the Method
*
*@param xpathToElement Description of the Parameter
*@param doc Description of the Parameter
*@return Description of the Return Value
*@exception CVXMLException Description of the Exception
*/
public static String textForElement(String xpathToElement, Document doc) throws CVXMLException {
String results = null;
try {
if (logger.isDebugEnabled()) logger.debug("getting textForElement using old way -- no cachedxpathapi");
Node n = XPathAPI.selectSingleNode(doc.getDocumentElement(), xpathExpression);
if (n != null) {
results = textForElement((Element)n);
}
} catch (CVXMLException e) {
e.appendLogInfo("Unable to find a node using the xpath : " + xpathToElement);
throw e;
} catch (Throwable t) {
if (logger.isDebugEnabled()) logger.debug("Error getting textForElement", t);
}
return results;
}
7. 取得Attibute的方法
//xml-apis.jar
public static String textForAttribute(Element parentElement, String attributeName) {
String attributeText = null;
Attr classAttribute = parentElement.getAttributeNode(attributeName);
if (classAttribute != null) {
attributeText = classAttribute.getValue();
}
return attributeText;
}
8. 设置text和attribute的方法
//xml-apis.jar
public static void setTextForElement(Element textElement, String textToBeUsed) {
if (textToBeUsed != null) {
if (textToBeUsed.length() > 0){
textToBeUsed = StringUtils.removeIncompatibilityCharacters(textToBeUsed);
}
if (textElement.hasChildNodes()) {
// search for a text or cdata node to set the value of
boolean found = false;
boolean done = false;
Node child = textElement.getFirstChild();
while (!found && !done) {
if (child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE) {
done = true;
found = true;
} else {
child = child.getNextSibling();
if (child == null) {
done = true;
}
}
}
if (found) {
child.setNodeValue(textToBeUsed);
} else {
//Node text = textElement.getOwnerDocument().createTextNode(textToBeUsed);//GR 04/01/2004 -- Changed to create CData Section instead
Node text = textElement.getOwnerDocument().createCDATASection(textToBeUsed);
textElement.appendChild(text);
}
}
else {
// no text nodes found to set a value for, so must create one
//textElement.appendChild(textElement.getOwnerDocument().createTextNode(textToBeUsed));//GR 04/01/2004 -- Changed to create CData Section instead
textElement.appendChild(textElement.getOwnerDocument().createCDATASection(textToBeUsed));
}
}
}
public static String removeIncompatibilityCharacters(String textStr) {
CharArrayWriter charArrayWriter = new CharArrayWriter();
for (int i = 0; i < textStr.length(); i++) {
if (Character.isDefined(textStr.charAt(i))) {
int charVal = (int) textStr.charAt(i);
// Control Characters --> NUL, SOH, STX, ETX, EOT, ENQ, ACK, BEL, BS
if (charVal >= 0x00 && charVal <= 0x08) {
continue;
}
// Control Characters --> CR, SO, SI, DLE, DC1, DC2, DC3, DC4, NAK, SYN, ETB, CAN, EM, SUB, ESC, FS, GS, RS, US
if (charVal >= 0x0B && charVal <= 0x1F) {
continue;
}
// The remaining characters are defined at http://www.w3.org/TR/2006/REC-xml-20060816/#charsets
if (charVal >= 0x7F && charVal <= 0x84) {
continue;
}
if (charVal >= 0x86 && charVal <= 0x9F) {
continue;
}
if (charVal >= 0xFDD0 && charVal <= 0xFDDF) {
continue;
}
if (charVal >= 0x1FFFE && charVal <= 0x1FFFF) {
continue;
}
if (charVal >= 0x2FFFE && charVal <= 0x2FFFF) {
continue;
}
if (charVal >= 0x3FFFE && charVal <= 0x3FFFF) {
continue;
}
if (charVal >= 0x4FFFE && charVal <= 0x4FFFF) {
continue;
}
if (charVal >= 0x5FFFE && charVal <= 0x5FFFF) {
continue;
}
if (charVal >= 0x6FFFE && charVal <= 0x6FFFF) {
continue;
}
if (charVal >= 0x7FFFE && charVal <= 0x7FFFF) {
continue;
}
if (charVal >= 0x8FFFE && charVal <= 0x8FFFF) {
continue;
}
if (charVal >= 0x9FFFE && charVal <= 0x9FFFF) {
continue;
}
if (charVal >= 0xAFFFE && charVal <= 0xAFFFF) {
continue;
}
if (charVal >= 0xBFFFE && charVal <= 0xBFFFF) {
continue;
}
if (charVal >= 0xCFFFE && charVal <= 0xCFFFF) {
continue;
}
if (charVal >= 0xDFFFE && charVal <= 0xDFFFF) {
continue;
}
if (charVal >= 0xEFFFE && charVal <= 0xEFFFF) {
continue;
}
if (charVal >= 0xFFFFE && charVal <= 0xFFFFF) {
continue;
}
if (charVal >= 0x10FFFE && charVal <= 0x10FFFF) {
continue;
}
charArrayWriter.write(charVal);
}
}
return new String(charArrayWriter.toCharArray());
}
public static void setTextForAttribute(Element parentElement, String attributeName, String attributeValue) {
parentElement.setAttribute(attributeName, attributeValue);
}
9. 创建Document
a. //xml-apis.jar
//Creates a new document object with the root node having the name: <code>rootElementName</code>\
public static Document createDocumentWithRoot(String rootElementName, boolean x) {
Document newRecordDoc = null;
if (rootElementName != null && !rootElementName.trim().equals("")) {
newRecordDoc = createDocument(true);
// Once the new document has been created, add the necessary root element
newRecordDoc.appendChild(newRecordDoc.createElement(rootElementName));
}
return newRecordDoc;
}
b. //Creates a new document object without the root node being set on the
public static Document createDocument(boolean x) {
Document newRecordDoc = null;
try {
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
newRecordDoc = docBuilder.newDocument();
} catch (Exception e) {
ExceptionLogWriter.logException(e, "DOMHelper.createDocument(). Problem instantiating a new DocumentBuilder");
}
return newRecordDoc;
}
10. 替换节点
a. //xml-apis.jar
public static Document replaceRootNodeName(String xml, String newValue) throws CVXMLException {
Document doc = stringToDocument(xml, true);
replaceRootNodeName(doc, newValue);
return doc;
}
b.
public static void replaceRootNodeName(Document doc, String newValue) {
replaceNodeName(doc, doc.getDocumentElement(), newValue);
}
c.
public static void replaceNodeName(Document doc, Element element, String newValue) {
//Create an element with the new name
Element element = doc.createElement(newValue);
// Copy the attributes to the new element
NamedNodeMap attrs = element.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
Attr attr2 = (Attr)doc.importNode(attrs.item(i), true);
element2.getAttributes().setNamedItem(attr2);
}
// Move all the children
while (element.hasChildNodes()) {
element2.appendChild(element.getFirstChild());
}
// Replace the old node with the new node
element.getParentNode().replaceChild(element2, element);
}
二. SAX 解析
class XMLDocument extends DefaultHandler {
Document doc;
String elementName = "";
String attribName = "";
String attribVal = "";
boolean addAttr = false;
Element currElement;
Element root;
String rootName;
boolean hasDocument = false;
boolean hasRoot = false;
int count = 0;
/** Constructor for the XMLDocument object */
XMLDocument() {
super();
hasDocument = false;
}
/**
*@param val Document
*/
XMLDocument(Document val) {
super();
doc = val;
hasDocument = true;
}
/**
* Method to set the Root
*
*@param val The new root value
*/
public void setRoot(String val) {
rootName = val;
hasRoot = true;
}
/**
* Method to add an attribute.
*
*@param element String containing the elementName
*@param attribute String containing the attribute name
*@param value String containing the attribute value
*/
public void addAttribute(String element, String attribute, String value) {
elementName = element;
attribName = attribute;
attribVal = value;
addAttr = true;
}
/**
*@exception SAXException If the root element name is missing
*/
public void startDocument() throws SAXException {
if (!hasDocument) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
doc = parser.newDocument();
} catch (Exception e) {
throw new SAXException(e);
}
if (rootName == null || rootName.equals("")) {
throw new SAXException("Missing root element name, call setRoot() first");
}
}
if (hasRoot) {
root = (Element)doc.createElement(rootName);
doc.appendChild(root);
}
}
/**
*@param uri String containing the uri
*@param localName String containing the localName
*@param rawName String containing the rawName
*@param atts Attributes
*@exception SAXException Description of the Exception
*/
public void startElement(String uri, String localName, String rawName, Attributes atts) throws SAXException {
// Assume the first element encountered is the root element
// Check the element to see if it is one we are interested in processing
if (hasRoot) {
if (!rawName.equalsIgnoreCase(rootName)) {
currElement = (Element)doc.createElement(rawName);
for (int i = 0; i < atts.getLength(); i++) {
currElement.setAttribute(atts.getQName(i), atts.getValue(i));
}
if (rawName.equals(elementName) && addAttr) {
// Add the new attribute if specified
currElement.setAttribute(attribName, attribVal);
}
root.appendChild(currElement);
} else {
currElement = (Element)doc.createElement(rawName);
for (int i = 0; i < atts.getLength(); i++) {
currElement.setAttribute(atts.getQName(i), atts.getValue(i));
}
}
} else {
// Create a new element - used for stringToDoc(String) method
if (count == 0) {
root = (Element)doc.createElement(rawName);
doc.appendChild(root);
}
currElement = (Element)doc.createElement(rawName);
for (int i = 0; i < atts.getLength(); i++) {
currElement.setAttribute(atts.getQName(i), atts.getValue(i));
}
root.appendChild(currElement);
count++;
}
}
/**
*@param ch Description of the Parameter
*@param start Description of the Parameter
*@param length Description of the Parameter
*@exception SAXException Description of the Exception
*/
public void characters(char[] ch, int start, int length) throws SAXException {
Text text = doc.createTextNode(new String(ch, start, length));
if (currElement != null) {
currElement.appendChild(text);
}
}
/**
* Description of the Method
*
*@return Description of the Return Value
*/
public Document document() {
return doc;
}
}
//xml-apis.jar
public Object process( InputSource is ) {
protected List tags = new ArrayList(0);
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating( strict );
SAXParser sp = spf.newSAXParser();
XMLReader xmlReader = sp.getXMLReader();
xmlReader.setContentHandler( this );
xmlReader.setErrorHandler( this );
if( entityResolver != null ) {
xmlReader.setEntityResolver( entityResolver );
}
xmlReader.parse( is );
if( tags.size() == 0 ) return finish( null );
return finish( tags.remove(0) );
}
MyProcess processor = new ProcessImpl(conf, rc);
//XMLBuilder extends XMLDocument 策略模式
XMLBuilder xb = new XMLBuilder(processor);
xb.process(new StringReader( ""));
三. xsl parse xml
//xml-apis.jar
protected void transformXml(String path, String documentXml) {
StreamSource xsl = new StreamSource(new File(xslFileName));
StringReader reader = new StringReader(documentXml);
StreamSource xml = new StreamSource(reader);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
Transformer transformer = null;
try {
transformer = TransformerFactory.newInstance().newTransformer(xsl);
}
try {
if(null != transformer) {
transformer.transform(xml, result);
}
}
xsl:
<root>
<xsl:template match="/book">
<xsl:if test="date/text()" >
<newnode><xsl:value-of select="date"/></facet>
</xsl:if>
<xsl:apply-templates select="Auther/lan"/>
</root>
<xsl:template match="Auther/lan">
<xsl:if test="position()=1">
<p><xsl:value-of select="key"/></p>
</xsl:if>
</xsl:template>
发表评论
-
介绍几款PDF转图片的开源工具
2011-09-09 00:40 4493最近项目中有个需求需要把PDF转成一张图。经过调查,有 ... -
jadclipse(反编译Eclipse插件)
2011-07-19 19:13 1620Jad Java decompiler plugin for ... -
Java开发时候的内存溢出
2011-07-13 17:33 1159这里以tomcat环境为例, ... -
class loader
2011-07-08 17:23 0Because Class.getResource() eve ... -
Jakarta-Common-BeanUtils使用笔记
2011-07-06 16:55 1302原文转发http://blog.csdn.net/fa ... -
基于MVC模式Struts框架研究
2011-04-13 20:02 1299不做web开发多年了, 可偶尔去面试的时候, 还是 ... -
Java反射与动态代理
2011-04-13 15:08 938这篇文章是 成富 先生在InfoQ上Java 深度历险系列的一 ... -
Java枚举类型
2011-04-04 19:50 754Tiger中的一个重要新特性是枚举构造,它是一种新的Java枚 ... -
Java 值传递的终极解释
2011-03-21 22:49 1940对于Java的值传递, 你真的了解么? Ja ... -
六种异常处理的陋习
2011-03-20 03:21 732你觉得自己是一个Java专 ... -
数组初始化
2011-03-20 02:40 835数组初始化,你觉得简单吗? a.如果你觉得简单,那请看下面的 ... -
Java 实现 hashCode 方法
2011-03-11 17:07 1132原文 http://www.javapractices.com ... -
Java 中 immutable class 以及怎样实现immutable 类
2011-03-11 16:47 1330原文 http://www.javapractices.com ... -
Java 内部类介绍
2011-02-16 17:14 949转载: http://zhidao.baidu.com/que ... -
Java 中的Clone 学习总结
2011-01-25 18:22 26971. 一个类需要实现clone. 一个最佳实践是它需要实现 C ... -
java 通过流, nio 移动文件或者文件夹
2011-01-04 17:54 1815我们用例子说明java怎样通过不同的方式移动文件或文件夹。 ... -
转 深入探讨SOAP、RPC和RMI
2010-12-17 00:34 1009这篇文章是从网上转下来的。 原文应该是写于2001年。 10 ... -
java 6 中的性能优化
2010-12-07 15:30 1408文章转载自: http://www ... -
创建强健,稳定的 JMS 系统
2010-12-07 15:21 950The most reliable way to produc ... -
Java Modifier Summary
2010-11-12 15:10 844<tbody> <tr> ...
相关推荐
使用java工具xml2axml.jar反编译AndroidManafest文件 通过xml2axml.jar工具反编译AndroidManafest文件 还原AndroidManafest.xml详细过程: 1、获取到apk 2、解压获取里面的AndroidManifest.xml文件 3、在xml2axml....
一、Idea关联的maven本地仓库配置文件settings.xml (1)必须使用默认文件名 D:\developsoft\javaweb\commonPlugins\maven\apache-maven-3.8.1_first\conf\settings.xml 二、Myeclipse关联的maven本地仓库配置文件...
xml加密(XML Encryption)是w3c加密xml的标准。这个加密过程包括加密xml文档的元素及其子元素,通过加密,xml的初始内容将被替换,但其xml格式仍然被完好的保留。 介绍 我们有3个加密xml的方法 1、仅仅使用对称...
TinyXML是一个简单小巧,可以很容易集成到其它程序中的C++ XML解析器。 它能做些什么 简单地说,TinyXML解析一个XML文档并由此生成一个可读可修改可保存的文档对象模型(DOM)。 XML的意思是“可扩展标记语言...
XML发展历史概述 XML文档组成元素 XML Schema组成元素 XML相关API
android开发中有时会想研究借鉴一下设计思路和UI风格,但解压apk包后 layout文件夹下xml文件一般都是加密的。在网上找到了一个工具,可以完美地解密xml文件,但这个工具的使用方法是:调cmd 然后...
vb中读写XML文件实例Dim XMLDoc As DOMDocument Dim root As IXMLDOMNode Dim xlst As IXMLDOMNodeList, xlst1 As IXMLDOMNodeList Dim xn As IXMLDOMNode Dim xnf As IXMLDOMNode Dim xe As IXMLDOMElement Set ...
XML(eXtensible Markup Language)是一种通用的文本格式,被广泛运用于数据交换和数据存储(虽然近年来 JSON 盛行,大有取代 XML 的趋势,但是对于一些已有系统和架构,比如 WebService,由于历史原因,仍旧会继续...
纯C语言解析xml字符串,有实例,保证可用,含makefile xmlparse.c xmlparse.h testxml.c 目录:/export/home/chcard/testxml 日志:/export/home/chcard/log testxml.c 是一个测试用例,包含了常用的方法,并有注解 ...
Altova XMLSpy是一款业界最畅销的XML编辑器,这款XMLSpy2013重点新增了智能修复、Java应用程序无缝集成、集成外部程序等新功能,而且本站提供的是中文破解版,能给用户带来极大的方便。 Altova XMLSpy主要用于建模,...
xml 与 bean 互相转换 工具类 1、bean类的属性需要遵守BEAN规范,否则 无法 读存BEAN值。 2、bean类的属性如果 是集合 只支持数组以及List、Map、Set。 3、bean类属性(boolean除外)前面两个字母要么全部小写,要么...
andxml汉化版是一个xml文件反编译工具,可与APKTOOL反编译配合使用,APK文件使用APKTool反编译生成XML文件后,就可以直接通过它进行汉化编辑 注意: 1、一键机器翻译会造成某些代码出现翻译错误现象,请人工识别。...
haarcascade_eye.xml haarcascade_eye_tree_eyeglasses.xml haarcascade_frontalcatface.xml haarcascade_frontalcatface_extended.xml haarcascade_frontalface_alt.xml haarcascade_frontalface_alt_tree.xml haar...
《XML》实验任务书 【2】 XML Schema [实验目的] 1、学习如何使用XMLSPY集成开发环境完成XML Schema相关的开发工作。 2、掌握XML Schema与DTD之间的区别,能够完成两者之间的转换;掌握在XML Schema中如何定义元素...
开源项目TinyXml项目所涉及的字符编码说明如下: 1. TinyXml函数调用接口的字符型参数,仅支持`窄字符`格式(char*),不兼容`宽字符`格式(wchar_t*)。 2. TinyXml函数提供的Xml内容解析功能,仅支持以ANSI编码和UTF...
java在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava...
易语言 xml解析 易语言 xml解析 易语言 xml解析 易语言 xml解析 易语言 xml解析 易语言 xml解析 易语言 xml解析 教程 带源码
tinyxml与tinyxml2两个版本的源码,操作xml很方便,解压可以直接使用.
动态生成Rss文件 Xml操作 Xml文件的修改动态生成Rss文件 Xml操作 Xml文件的修改动态生成Rss文件 Xml操作 Xml文件的修改动态生成Rss文件 Xml操作 Xml文件的修改动态生成Rss文件 Xml操作 Xml文件的修改动态生成Rss文件...
主要介绍了Maven pom.xml与settings.xml详解的相关资料,这里对pom.xml与setting.xml详细的研究说明,需要的朋友可以参考下