📄 xmltools.java
字号:
/*
* This file is part of Caliph & Emir.
*
* Caliph & Emir is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Caliph & Emir is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Caliph & Emir; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Copyright statement:
* --------------------
* (c) 2005 by Werner Klieber (werner@klieber.info)
* http://caliph-emir.sourceforge.net
*/
package at.wklieber.tools;
import at.wklieber.Settings;
import org.apache.log4j.Category;
import org.apache.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.DOMOutputter;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jdom.xpath.XPath;
import java.io.*;
import java.net.URL;
import java.util.*;
public class XmlTools {
static Category cat = Logger.getLogger(XmlTools.class.getName());
private static Console console = Console.getReference();
private static Settings cfg = Settings.getReference();
static final String XML_PATH_SEPARATOR = "/\\,. ;";
public XmlTools() {
}
/**
* This method parses the location-String and walks through the JDOM tree until
* the right child-Element is reached and returns this Element. If create is
* false, the default value is returned if a child doesn't exist. If create is
* true, non existing children are created.
* Note: if namespace is not null, the namespace is added to each new created element
* Note: support for attributes is not implemented
* Note: if there are more than one tag with the same name on a
* level, the one retrieved from getChild() is used (the first one).
* Note: high level methods for simpleXpath is in XmlTemplate class
*/
public static org.jdom.Element simpleXpath(org.jdom.Element rootElement1, String location1,
org.jdom.Element default1, boolean create1) {
return simpleXpath(rootElement1, location1, null, default1, create1);
}
public static org.jdom.Element simpleXpath(org.jdom.Element rootElement1, String location1,
Namespace nameSpace, org.jdom.Element default1, boolean create1) {
org.jdom.Element returnValue = default1;
try {
//System.out.println("go for: " + location1);
if ((location1 == null) || (location1.length() == 0) || (rootElement1 == null)) {
return returnValue;
}
String location = location1.trim();
StringTokenizer tokens = new StringTokenizer(location, XML_PATH_SEPARATOR, false);
// walk down the xml-hierachy
Element baseElement = rootElement1;
boolean isRootElement = true;
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken();
if (baseElement == null) ;
Element newBase;
if (isRootElement) {
newBase = baseElement;
isRootElement = false;
} else {
if (nameSpace == null) {
newBase = baseElement.getChild(token);
} else {
newBase = baseElement.getChild(token, nameSpace);
}
}
if (newBase == null) { // this child doesn't exist
if (create1) {
if (nameSpace == null) {
newBase = new Element(token);
} else {
newBase = new Element(token, nameSpace);
}
baseElement.addContent(newBase);
//console.echo("Name: " + newBase.getName() + ", ns pre: <" + newBase.getNamespace().getPrefix() + ">, url: <" + newBase.getNamespace().getURI() + ">");
//console.echo(XmlTools.documentToString(rootElement1));
} else {
return returnValue;
}
} // end if baseElement
baseElement = newBase;
} // end while
returnValue = baseElement;
} catch (Exception e) {
cat.error(e);
}
return returnValue;
} // end method
// same as obove, just with Document instead of Element
public static org.jdom.Element simpleXpath(org.jdom.Document document1, String location1,
org.jdom.Element default1, boolean create1) {
org.jdom.Element returnValue = default1;
if ((location1 == null) || (location1.length() == 0) || (document1 == null)) {
return returnValue;
}
return simpleXpath(document1.getRootElement(), location1, returnValue, create1);
} // end method
public static String documentToString(Document doc) {
String ret = "";
if (doc != null) {
try {
XMLOutputter xml_out = new XMLOutputter(Format.getPrettyFormat());
StringWriter out = new StringWriter();
xml_out.output(doc, out);
ret = out.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
return ret;
}
public static String documentToString(org.jdom.Element elem) {
String ret = "";
if (elem != null) {
org.jdom.Element elem2 = (org.jdom.Element) elem.clone(); // we need an Element with no parent
Document doc = new Document(elem2);
ret = documentToString(doc);
}
return ret;
}
public static Document stringToDocument(String strDoc1, boolean doValidate1) {
return stringToDocument(strDoc1, doValidate1, null);
}
public static Document stringToDocument(String strDoc1, boolean doValidate1, Document defaultValue1) {
Document returnValue = defaultValue1;
if (strDoc1 == null) {
return returnValue;
}
try {
Document temp = null;
SAXBuilder builder = new SAXBuilder();
/*
File f = File.createTempFile("xml", null);
FileTools.saveToFile(f.getAbsolutePath(), strDoc1);
File in = new File(f.getAbsolutePath());
*/
StringReader strIn = new StringReader(strDoc1);
builder.setValidation(doValidate1);
temp = builder.build(strIn);
if (temp != null) {
returnValue = temp;
}
} catch (Exception e) {
cat.error(e);
}
return returnValue;
}
public static Document fileToDocument(String fileName1, boolean doValidate1) {
Document ret = null;
if (fileName1 == null) {
cat.error("Filename is NULL");
return ret;
}
String filename = FileTools.resolvePath(fileName1);
cat.debug("loading file" + filename);
if (!FileTools.existsFile(filename)) {
cat.error("File \"" + filename + "\" doesn't exist");
return ret;
}
Document temp = null;
try {
SAXBuilder builder = new SAXBuilder();
File inFile = new File(filename);
builder.setValidation(doValidate1);
if (!doValidate1) {
builder.setDTDHandler(null);
}
temp = builder.build(inFile);
} catch (JDOMException je) {
cat.error(je);
} catch (Exception e) {
cat.error(e);
}
ret = temp;
return ret;
}
// this method replaces the content of "target" with the content of "source".
// this means everything: children, texts, ...
// not tested with attributes
public static void replaceElement(org.jdom.Element target, org.jdom.Element source) {
//target.removeChildren();
target.getChildren().clear();
//List new_copy = source.getChildren();
//Element new_copy = (Element) source.clone(); // without parent
List children = source.getChildren();
Iterator it = children.iterator();
Vector newList = new Vector();
while (it.hasNext()) {
// get child without parent
org.jdom.Element child = (org.jdom.Element) it.next();
newList.add(child.clone());
}
//target.setChildren(newList);
target.addContent(newList);
}
// convert a JDOM - document to a W3C-Element
public static org.w3c.dom.Document jdom2w3c(Document jdomElement1, org.w3c.dom.Document default1) {
org.w3c.dom.Document returnValue = default1;
try {
DOMOutputter outputter = new DOMOutputter();
returnValue = outputter.output(jdomElement1);
} catch (Exception e) {
cat.error(e);
}
return returnValue;
}
// convert a JDOM - Element to a W3C-Element
public static org.w3c.dom.Element jdom2w3c(Document jdomElement1, org.w3c.dom.Element default1) {
org.w3c.dom.Element returnValue = default1;
try {
DOMOutputter outputter = new DOMOutputter();
//returnValue = outputter.output(jdomElement1.getRootElement());
org.w3c.dom.Document d = outputter.output(jdomElement1);
returnValue = d.getDocumentElement();
//org.w3c.dom.Document resultDocument = outputter.output(jdomElement1);
//returnValue = Document.
} catch (Exception e) {
cat.error(e);
}
return returnValue;
}
/**
* Reads the file "fileName" and converts it to a JDOM-Document.
* If anything fails the input-default Document "doc" is returned
*/
public static Document readFromFile(String fileName, Document doc) {
Document returnValue = null;
try {
SAXBuilder builder = new SAXBuilder();
//File file = new File(new URI(fileName));
cat.debug("READ: " + fileName);
//File file = new File(FileTools.removeFileUrlPrefix(fileName));
returnValue = builder.build(new URL(FileTools.setUrlPrefix(fileName)));
} catch (Exception je) {
console.error("ERROR while reading file \"" + fileName + "\"");
je.printStackTrace();
returnValue = doc;
}
return returnValue;
}
/**
* Reads the file "fileName" and converts it to a e3c Element.
* If anything fails the input-default Element "default1" is returned
*/
public static org.w3c.dom.Element readFromFileW3c(String fileName1, org.w3c.dom.Element default1) {
org.w3c.dom.Element returnValue = default1;
Document doc = readFromFile(fileName1, null);
if (doc != null) {
returnValue = jdom2w3c(doc, returnValue);
}
return returnValue;
}
/**
* Reads the file "fileName" and converts it to a w3c document.
* If anything fails the input-default Document "default1" is returned
*/
public static org.w3c.dom.Document readFromFileW3c(String fileName1, org.w3c.dom.Document default1) {
org.w3c.dom.Document returnValue = default1;
Document doc = fileToDocument(fileName1, false);
if (doc != null) {
returnValue = jdom2w3c(doc, returnValue);
}
return returnValue;
}
// writes a JDOM document to a file in UFT
public static void saveToFile(String fname, Document doc) {
try {
XMLOutputter xml_out = new XMLOutputter(Format.getPrettyFormat());
String data = null;
if (doc != null) {
StringWriter out = new StringWriter();
xml_out.output(doc, out);
data = out.toString();
}
if (data == null)
data = "";
cat.debug("write string in utf8 to: " + fname);
FileTools.saveToFileUtf8(fname, data);
} catch (Exception e) {
e.printStackTrace();
}
} // end method
// validate an xml-String against an given dtd
public static boolean isDocumentValid(String strDoc1, String dtdFile) {
boolean ret = false;
cat.debug("Input-XML-String: " + strDoc1);
if (!FileTools.existsFile(dtdFile)) {
cat.error("File \"" + dtdFile + "\" not found. Unable to validate");
return ret;
}
Document docOrginal = stringToDocument(strDoc1, false);
if (docOrginal == null) {
cat.error("XML-String is not a valid XML-syntax");
return ret;
}
try {
//org.jdom.Element getRootElement;
//getRootElement = docOrginal.getRootElement();
String rootElement = docOrginal.getRootElement().getName();
rootElement = rootElement.trim();
cat.debug("Root-Element: <" + rootElement + ">");
String fileName = FileTools.resolvePath(dtdFile);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -