001: /*
002: * JFox - The most lightweight Java EE Application Server!
003: * more details please visit http://www.huihoo.org/jfox or http://www.jfox.org.cn.
004: *
005: * JFox is licenced and re-distributable under GNU LGPL.
006: */
007: package org.jfox.util;
008:
009: import java.io.File;
010: import java.io.FileOutputStream;
011: import java.io.IOException;
012: import java.io.StringReader;
013: import java.io.StringWriter;
014: import java.io.Writer;
015: import java.net.URL;
016: import java.util.ArrayList;
017: import java.util.Arrays;
018: import java.util.List;
019: import javax.xml.namespace.QName;
020: import javax.xml.parsers.DocumentBuilderFactory;
021: import javax.xml.parsers.ParserConfigurationException;
022: import javax.xml.transform.OutputKeys;
023: import javax.xml.transform.Result;
024: import javax.xml.transform.Source;
025: import javax.xml.transform.Transformer;
026: import javax.xml.transform.TransformerFactory;
027: import javax.xml.transform.dom.DOMSource;
028: import javax.xml.transform.stream.StreamResult;
029: import javax.xml.xpath.XPath;
030: import javax.xml.xpath.XPathExpressionException;
031: import javax.xml.xpath.XPathFactory;
032:
033: import org.w3c.dom.Attr;
034: import org.w3c.dom.CDATASection;
035: import org.w3c.dom.Document;
036: import org.w3c.dom.Element;
037: import org.w3c.dom.Node;
038: import org.w3c.dom.NodeList;
039: import org.w3c.dom.Text;
040: import org.xml.sax.InputSource;
041: import org.xml.sax.SAXException;
042:
043: /**
044: * XML Utilities
045: *
046: * @author <a href="mailto:jfox.young@gmail.com">Young Yang</a>
047: */
048: public class XMLUtils {
049:
050: private final static DocumentBuilderFactory dbf = DocumentBuilderFactory
051: .newInstance();
052: private final static TransformerFactory tf = TransformerFactory
053: .newInstance();
054:
055: private final static XPathFactory xpf = XPathFactory.newInstance();
056:
057: static {
058: // tf.setAttribute("indent-number", 4);
059: dbf.setValidating(false);
060: dbf.setNamespaceAware(true);
061: }
062:
063: private XMLUtils() {
064:
065: }
066:
067: public static List<Element> getChildElements(Element parentElement) {
068: NodeList nodeList = parentElement.getChildNodes();
069: List<Element> childElements = new ArrayList<Element>(nodeList
070: .getLength());
071: for (int i = 0; i < nodeList.getLength(); i++) {
072: Node childNode = nodeList.item(0);
073: if (childNode.getNodeType() == Node.ELEMENT_NODE) {
074: childElements.add((Element) childNode);
075: }
076: }
077: return childElements;
078: }
079:
080: public static Element getChildElementByTagName(
081: Element parentElement, String childTag) {
082: for (Node temp = parentElement.getFirstChild(); temp != null; temp = temp
083: .getNextSibling())
084: if (temp.getNodeType() == Node.ELEMENT_NODE
085: && childTag.equals(temp.getNodeName())) {
086: return (Element) temp;
087: }
088: return null;
089: }
090:
091: public static List<Element> getChildElementsByTagName(
092: Element parentElement, String childTag) {
093: NodeList nodelist = parentElement.getChildNodes();
094: List<Element> nodes = new ArrayList<Element>();
095: for (int i = 0; i < nodelist.getLength(); i++) {
096: Node temp = nodelist.item(i);
097: if (temp.getNodeType() == Node.ELEMENT_NODE
098: && temp.getNodeName().equals(childTag)) {
099: nodes.add((Element) temp);
100: }
101: }
102: return nodes;
103: }
104:
105: public static String getChildElementValueByTagName(
106: Element parentElement, String childTag) {
107: if (childTag.equals(parentElement.getNodeName())) {
108: return getNodeValue(parentElement);
109: }
110: for (Node temp = parentElement.getFirstChild(); temp != null; temp = temp
111: .getNextSibling()) {
112: if (temp.getNodeType() == Node.ELEMENT_NODE
113: && childTag.equals(temp.getNodeName())) {
114: return getNodeValue(temp);
115: }
116: }
117: return null;
118: }
119:
120: public static List<Element> getElementsByTagName(Element element,
121: String tagName) {
122: ArrayList<Element> children = new ArrayList<Element>();
123: if (element != null && tagName != null) {
124: NodeList nodes = element.getElementsByTagName(tagName);
125: for (int i = 0; i < nodes.getLength(); i++) {
126: Node child = nodes.item(i);
127: children.add((Element) child);
128: }
129: }
130: return children;
131: }
132:
133: public static List<Element> getElementsByTagNames(Element element,
134: String[] tagNames) {
135: List<Element> children = new ArrayList<Element>();
136: if (element != null && tagNames != null) {
137: List tagList = Arrays.asList(tagNames);
138: NodeList nodes = element.getChildNodes();
139: for (int i = 0; i < nodes.getLength(); i++) {
140: Node child = nodes.item(i);
141: if (child.getNodeType() == Node.ELEMENT_NODE
142: && tagList.contains(((Element) child)
143: .getTagName())) {
144: children.add((Element) child);
145: }
146: }
147: }
148: return children;
149: }
150:
151: public static String getNodeValue(Node node) {
152: if (node == null) {
153: return null;
154: } else if (node instanceof Text) {
155: return node.getNodeValue().trim();
156: } else if (node instanceof Element) {
157: node.normalize();
158: Node temp = node.getFirstChild();
159: if (temp != null && (temp instanceof Text))
160: return temp.getNodeValue().trim();
161: else
162: return "";
163: } else {
164: return node.getNodeValue().trim();
165: }
166: }
167:
168: public static String getAtrributeValue(Node node, String attribute) {
169: Node _node = node.getAttributes().getNamedItem(attribute);
170: return getNodeValue(_node);
171: }
172:
173: /**
174: * get the xml root document of the xml descriptor
175: *
176: * @param url the xml descriptor url
177: * @return XML document
178: * @throws IOException if failed to create XML document
179: * @throws ParserConfigurationException e
180: * @throws SAXException e
181: */
182: public static Document loadDocument(URL url) throws IOException,
183: ParserConfigurationException, SAXException {
184: return dbf.newDocumentBuilder().parse(FileUtils.toFile(url));
185: }
186:
187: /**
188: * parse document from xml String
189: *
190: * @param xml xml string
191: * @throws IOException if failed to create XML document
192: * @throws ParserConfigurationException e
193: * @throws SAXException e
194: */
195: public static Document loadDocument(String xml) throws IOException,
196: ParserConfigurationException, SAXException {
197: return dbf.newDocumentBuilder().parse(
198: new InputSource(new StringReader(xml)));
199: }
200:
201: /**
202: * new document
203: */
204: public static Document newDocument() {
205: try {
206: return dbf.newDocumentBuilder().newDocument();
207: } catch (Exception e) {
208: throw new RuntimeException(e);
209: }
210: }
211:
212: /**
213: * 为 parent Node å¢žåŠ ä¸€ä¸ª TextElement
214: *
215: * @param parent 父节点
216: * @param name element name
217: * @param value element value
218: * @return å¢žåŠ çš„ element
219: */
220: public static Element addTextElement(Node parent, String name,
221: String value) {
222: return addTextElement(parent, name, value, null);
223: }
224:
225: /**
226: * 为 parent Node å¢žåŠ ä¸€ä¸ª TextElement,å?¯å®šä¹‰è¯¥Element 的属性。
227: *
228: * @param parent parent node
229: * @param name node name
230: * @param value node value
231: * @param attrs atrributs
232: */
233: public static Element addTextElement(Node parent, String name,
234: String value, Attr[] attrs) {
235: Element element;
236: if (parent instanceof Document) {
237: element = ((Document) parent).createElement(name);
238: } else {
239: element = parent.getOwnerDocument().createElement(name);
240: }
241:
242: if (attrs != null && attrs.length > 0) {
243: for (Attr attr : attrs) {
244: element.setAttributeNode(attr);
245: }
246: }
247:
248: if (value != null) {
249: element.setTextContent(value);
250: }
251: parent.appendChild(element);
252: return element;
253: }
254:
255: /**
256: * Add a CDATA element.
257: *
258: * @param parent parent node
259: * @param name node name
260: * @param data node data
261: */
262: public static Element addCDATAElement(Node parent, String name,
263: String data) {
264: return addCDATAElement(parent, name, data, null);
265: }
266:
267: /**
268: * Add a CDATA element with attributes.
269: * <p/>
270: * NOTE: Serializing a XML document via TRAX changes "\r\n" to "\r\r\n" in
271: * a CDATA section. Serializing with the Xalan XMLSerializer works fine.
272: *
273: * @param parent parent node
274: * @param name node name
275: * @param data node data
276: * @param attrs attributes
277: */
278: public static Element addCDATAElement(Node parent, String name,
279: String data, Attr[] attrs) {
280: Element element;
281: CDATASection cdata;
282: if (parent instanceof Document) {
283: element = ((Document) parent).createElement(name);
284: /*
285: * Creates a <code>CDATASection</code> node whose value is the
286: * specified.
287: */
288: cdata = ((Document) parent).createCDATASection(data);
289: } else {
290: element = parent.getOwnerDocument().createElement(name);
291: cdata = parent.getOwnerDocument().createCDATASection(data);
292: }
293:
294: if (attrs != null && attrs.length > 0) {
295: for (Attr attr : attrs) {
296: element.setAttributeNode(attr);
297: }
298: }
299:
300: element.appendChild(cdata);
301: parent.appendChild(element);
302: return element;
303: }
304:
305: /**
306: * 为 parent Node å¢žåŠ ä¸€ä¸ªç©ºçš„ Element
307: *
308: * @param parent 父节点
309: * @param name element name
310: * @param attrs element çš„ attributes
311: * @return å¢žåŠ çš„ element
312: */
313: public static Element addElement(Node parent, String name,
314: Attr[] attrs) {
315: Element element;
316: if (parent instanceof Document) {
317: element = ((Document) parent).createElement(name);
318: } else {
319: element = parent.getOwnerDocument().createElement(name);
320: }
321: if (attrs != null && attrs.length > 0) {
322: for (Attr attr : attrs) {
323: element.setAttributeNode(attr);
324: }
325: }
326: parent.appendChild(element);
327: return element;
328: }
329:
330: public static Element addElement(Element parent,
331: Element childElement) {
332: Node childNode = parent.getOwnerDocument().importNode(
333: childElement, true);
334: parent.appendChild(childNode);
335: return parent;
336: }
337:
338: /**
339: * 创建 Attribute
340: *
341: * @param document xml document
342: * @param name node name
343: * @param value node value
344: * @return Attr
345: */
346: public static Attr createAttribute(Document document, String name,
347: String value) {
348: Attr attr = document.createAttribute(name);
349: attr.setTextContent(value);
350: return attr;
351: }
352:
353: /**
354: * å°†document转æˆ?å—符串
355: *
356: * @param node node
357: */
358: public static String toXMLString(Node node) {
359: if (node == null) {
360: return "";
361: }
362: try {
363: Transformer tran = tf.newTransformer();
364: tran.setOutputProperty(OutputKeys.INDENT, "yes");
365: StringWriter swriter = new StringWriter();
366: Source src = new DOMSource(node);
367: Result res = new StreamResult(swriter);
368: tran.transform(src, res);
369: return swriter.getBuffer().toString();
370: } catch (Exception e) {
371: e.printStackTrace();
372: return "";
373: }
374: }
375:
376: public static void toWriter(Document doc, Writer writer) {
377: if (doc == null || writer == null) {
378: return;
379: }
380: try {
381: Transformer tran = tf.newTransformer();
382: tran.setOutputProperty(OutputKeys.INDENT, "yes");
383: Source src = new DOMSource(doc);
384: Result res = new StreamResult(writer);
385: tran.transform(src, res);
386: } catch (Exception e) {
387: e.printStackTrace();
388: }
389: }
390:
391: public static Object evaluateXpath(Document doc, String xpath,
392: QName returnType) throws XPathExpressionException {
393: XPath path = xpf.newXPath();
394: return path.evaluate(xpath, doc, returnType);
395: }
396:
397: public static void main2() {
398: Document document = XMLUtils.newDocument();
399:
400: Element rspNode = XMLUtils.addElement(document, "response",
401: new Attr[] { XMLUtils.createAttribute(document, "type",
402: "LoginMessage.MESSAGE_TYPE") });
403:
404: XMLUtils.addTextElement(rspNode, "username",
405: "userContext.getUser().getUsername()");
406: XMLUtils.addTextElement(rspNode, "password",
407: "userContext.getUser().getPassword()");
408: XMLUtils.addTextElement(rspNode, "result", "successful");
409: XMLUtils.addTextElement(rspNode, "sessionId", "getSession()>");
410: XMLUtils.addCDATAElement(rspNode, "sessionId",
411: "getSession()]]>");
412:
413: Element childsElement = XMLUtils.addTextElement(rspNode,
414: "childs", null, null);
415: XMLUtils.addTextElement(childsElement, "child", "1");
416: System.out.println(XMLUtils.toXMLString(document));
417: }
418:
419: public static void main(String[] args) throws Exception {
420: Document doc = XMLUtils.loadDocument(new File(
421: "test-components.xml").toURI().toURL());
422: Element node = (Element) doc.getDocumentElement()
423: .getElementsByTagName("description").item(0);
424: node.setTextContent("Helo,World!");
425: String xml = XMLUtils.toXMLString(doc);
426: FileOutputStream out = new FileOutputStream(
427: "test-components.xml");
428: IOUtils.write(xml, out);
429: out.close();
430:
431: }
432: }
|