Java Tutorial/XML/Node — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 05:18, 1 июня 2010
Содержание
- 1 Add another element after the first child of the root element
- 2 Add a text node before the last child of the element
- 3 Add a text node in front of the new item element
- 4 Add a text node to the beginning of the element
- 5 Add a text node to the element
- 6 Adding a Text Node to a DOM Document
- 7 Change a particular node in XML
- 8 Compare two DOM Nodes
- 9 Compare two DOM Nodes from JBoss
- 10 Convert node element To String
- 11 Convert NodeList To Node Array
- 12 Copies the source tree into the specified place in a destination tree.
- 13 Create a new element and move the middle text node to it
- 14 DOM helper for root element
- 15 Find the first text descendent node of an element
- 16 Get the first text node associated with this element
- 17 Get the text node
- 18 Move all children of the element in front of the element
- 19 Remove All nodes
- 20 Remove this node from its parent.
- 21 Removing a Node from a DOM Document
- 22 Returns a first child DOM Node of type ELEMENT_NODE for the specified Node
- 23 Returns a list of value for the given node
- 24 Returns the value of the child node with the given name
- 25 Search earlier siblings for a given node
- 26 Search our next siblings for a given node
- 27 Search up the tree for a given node
- 28 Simplified implementation of a Node from a Document Object Model (DOM)
- 29 Split the node at the beginning of the word
Add another element after the first child of the root element
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.rument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getElementById("key1");
element = doc.createElement("root");
doc.appendChild(element);
Element element2 = doc.createElement("item");
element.insertBefore(element2, element.getFirstChild().getNextSibling());
}
}
Add a text node before the last child of the element
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.rument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getElementById("key1");
element = doc.createElement("root");
doc.appendChild(element);
element.insertBefore(doc.createTextNode("C"), element.getLastChild());
}
}
Add a text node in front of the new item element
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.rument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getElementById("key1");
element = doc.createElement("root");
doc.appendChild(element);
element.getParentNode().insertBefore(doc.createTextNode("B"), element);
}
}
Add a text node to the beginning of the element
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.rument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getElementById("key1");
element = doc.createElement("root");
doc.appendChild(element);
element.insertBefore(doc.createTextNode("A"), element.getFirstChild());
}
}
Add a text node to the element
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.rument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getElementById("key1");
element = doc.createElement("root");
doc.appendChild(element);
element.appendChild(doc.createTextNode("D"));
}
}
Adding a Text Node to a DOM Document
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getDocumentElement();
Text text = doc.createTextNode("data\n");
element.appendChild(text);
text = doc.createTextNode("<>&\""");
element.appendChild(text);
}
}
Change a particular node in XML
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class Main {
public static void main(String[] args) throws Exception {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(
new InputSource("data.xml"));
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList) xpath.evaluate("//employee/name[text()="old"]", doc,
XPathConstants.NODESET);
for (int idx = 0; idx < nodes.getLength(); idx++) {
nodes.item(idx).setTextContent("new value");
}
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(new DOMSource(doc), new StreamResult(new File("data_new.xml")));
}
}
Compare two DOM Nodes
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
/**
* @version $Rev: 514087 $ $Date: 2007-03-03 01:13:40 -0500 (Sat, 03 Mar 2007) $
*/
public class DOMUtils {
private static void trimEmptyTextNodes(Node node) {
Element element = null;
if (node instanceof Document) {
element = ((Document) node).getDocumentElement();
} else if (node instanceof Element) {
element = (Element) node;
} else {
return;
}
List<Node> nodesToRemove = new ArrayList<Node>();
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child instanceof Element) {
trimEmptyTextNodes(child);
} else if (child instanceof Text) {
Text t = (Text) child;
if (t.getData().trim().length() == 0) {
nodesToRemove.add(child);
}
}
}
for (Node n : nodesToRemove) {
element.removeChild(n);
}
}
public static void compareNodes(Node expected, Node actual, boolean trimEmptyTextNodes)
throws Exception {
if (trimEmptyTextNodes) {
trimEmptyTextNodes(expected);
trimEmptyTextNodes(actual);
}
compareNodes(expected, actual);
}
public static void compareNodes(Node expected, Node actual) throws Exception {
if (expected.getNodeType() != actual.getNodeType()) {
throw new Exception("Different types of nodes: " + expected + " " + actual);
}
if (expected instanceof Document) {
Document expectedDoc = (Document) expected;
Document actualDoc = (Document) actual;
compareNodes(expectedDoc.getDocumentElement(), actualDoc.getDocumentElement());
} else if (expected instanceof Element) {
Element expectedElement = (Element) expected;
Element actualElement = (Element) actual;
// compare element names
if (!expectedElement.getLocalName().equals(actualElement.getLocalName())) {
throw new Exception("Element names do not match: " + expectedElement.getLocalName() + " "
+ actualElement.getLocalName());
}
// compare element ns
String expectedNS = expectedElement.getNamespaceURI();
String actualNS = actualElement.getNamespaceURI();
if ((expectedNS == null && actualNS != null)
|| (expectedNS != null && !expectedNS.equals(actualNS))) {
throw new Exception("Element namespaces names do not match: " + expectedNS + " " + actualNS);
}
String elementName = "{" + expectedElement.getNamespaceURI() + "}"
+ actualElement.getLocalName();
// compare attributes
NamedNodeMap expectedAttrs = expectedElement.getAttributes();
NamedNodeMap actualAttrs = actualElement.getAttributes();
if (countNonNamespaceAttribures(expectedAttrs) != countNonNamespaceAttribures(actualAttrs)) {
throw new Exception(elementName + ": Number of attributes do not match up: "
+ countNonNamespaceAttribures(expectedAttrs) + " "
+ countNonNamespaceAttribures(actualAttrs));
}
for (int i = 0; i < expectedAttrs.getLength(); i++) {
Attr expectedAttr = (Attr) expectedAttrs.item(i);
if (expectedAttr.getName().startsWith("xmlns")) {
continue;
}
Attr actualAttr = null;
if (expectedAttr.getNamespaceURI() == null) {
actualAttr = (Attr) actualAttrs.getNamedItem(expectedAttr.getName());
} else {
actualAttr = (Attr) actualAttrs.getNamedItemNS(expectedAttr.getNamespaceURI(),
expectedAttr.getLocalName());
}
if (actualAttr == null) {
throw new Exception(elementName + ": No attribute found:" + expectedAttr);
}
if (!expectedAttr.getValue().equals(actualAttr.getValue())) {
throw new Exception(elementName + ": Attribute values do not match: "
+ expectedAttr.getValue() + " " + actualAttr.getValue());
}
}
// compare children
NodeList expectedChildren = expectedElement.getChildNodes();
NodeList actualChildren = actualElement.getChildNodes();
if (expectedChildren.getLength() != actualChildren.getLength()) {
throw new Exception(elementName + ": Number of children do not match up: "
+ expectedChildren.getLength() + " " + actualChildren.getLength());
}
for (int i = 0; i < expectedChildren.getLength(); i++) {
Node expectedChild = expectedChildren.item(i);
Node actualChild = actualChildren.item(i);
compareNodes(expectedChild, actualChild);
}
} else if (expected instanceof Text) {
String expectedData = ((Text) expected).getData().trim();
String actualData = ((Text) actual).getData().trim();
if (!expectedData.equals(actualData)) {
throw new Exception("Text does not match: " + expectedData + " " + actualData);
}
}
}
private static int countNonNamespaceAttribures(NamedNodeMap attrs) {
int n = 0;
for (int i = 0; i < attrs.getLength(); i++) {
Attr attr = (Attr) attrs.item(i);
if (!attr.getName().startsWith("xmlns")) {
n++;
}
}
return n;
}
}
Compare two DOM Nodes from JBoss
/**
* JBoss, Home of Professional Open Source
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* @author
* @version <tt>$Revision: 3282 $</tt> $Id: XMLUtil.java 3282 2007-11-01
* 15:32:29Z timfox $
*/
public class Utils {
public static void assertEquivalent(Node node, Node node2) {
if (node == null) {
throw new IllegalArgumentException("the first node to be compared is null");
}
if (node2 == null) {
throw new IllegalArgumentException("the second node to be compared is null");
}
if (!node.getNodeName().equals(node2.getNodeName())) {
throw new IllegalArgumentException("nodes have different node names");
}
int attrCount = 0;
NamedNodeMap attrs = node.getAttributes();
if (attrs != null) {
attrCount = attrs.getLength();
}
int attrCount2 = 0;
NamedNodeMap attrs2 = node2.getAttributes();
if (attrs2 != null) {
attrCount2 = attrs2.getLength();
}
if (attrCount != attrCount2) {
throw new IllegalArgumentException("nodes hava a different number of attributes");
}
outer: for (int i = 0; i < attrCount; i++) {
Node n = attrs.item(i);
String name = n.getNodeName();
String value = n.getNodeValue();
for (int j = 0; j < attrCount; j++) {
Node n2 = attrs2.item(j);
String name2 = n2.getNodeName();
String value2 = n2.getNodeValue();
if (name.equals(name2) && value.equals(value2)) {
continue outer;
}
}
throw new IllegalArgumentException("attribute " + name + "=" + value + " doesn"t match");
}
boolean hasChildren = node.hasChildNodes();
if (hasChildren != node2.hasChildNodes()) {
throw new IllegalArgumentException("one node has children and the other doesn"t");
}
if (hasChildren) {
NodeList nl = node.getChildNodes();
NodeList nl2 = node2.getChildNodes();
short[] toFilter = new short[] { Node.TEXT_NODE, Node.ATTRIBUTE_NODE, Node.ruMENT_NODE };
List nodes = filter(nl, toFilter);
List nodes2 = filter(nl2, toFilter);
int length = nodes.size();
if (length != nodes2.size()) {
throw new IllegalArgumentException("nodes hava a different number of children");
}
for (int i = 0; i < length; i++) {
Node n = (Node) nodes.get(i);
Node n2 = (Node) nodes2.get(i);
assertEquivalent(n, n2);
}
}
}
private static List filter(NodeList nl, short[] typesToFilter) {
List nodes = new ArrayList();
outer: for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
short type = n.getNodeType();
for (int j = 0; j < typesToFilter.length; j++) {
if (typesToFilter[j] == type) {
continue outer;
}
}
nodes.add(n);
}
return nodes;
}
}
Convert node element To String
/**
* JBoss, Home of Professional Open Source
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* @author
* @version <tt>$Revision: 3282 $</tt> $Id: XMLUtil.java 3282 2007-11-01
* 15:32:29Z timfox $
*/
public class Utils {
public static String elementToString(Node n) {
String name = n.getNodeName();
short type = n.getNodeType();
if (Node.CDATA_SECTION_NODE == type) {
return "<![CDATA[" + n.getNodeValue() + "]]>";
}
if (name.startsWith("#")) {
return "";
}
StringBuffer sb = new StringBuffer();
sb.append("<").append(name);
NamedNodeMap attrs = n.getAttributes();
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
Node attr = attrs.item(i);
sb.append(" ").append(attr.getNodeName()).append("=\"").append(attr.getNodeValue()).append(
"\"");
}
}
String textContent = null;
NodeList children = n.getChildNodes();
if (children.getLength() == 0) {
if ((textContent = XMLUtil.getTextContent(n)) != null && !"".equals(textContent)) {
sb.append(textContent).append("</").append(name).append(">");
;
} else {
sb.append("/>").append("\n");
}
} else {
sb.append(">").append("\n");
boolean hasValidChildren = false;
for (int i = 0; i < children.getLength(); i++) {
String childToString = elementToString(children.item(i));
if (!"".equals(childToString)) {
sb.append(childToString);
hasValidChildren = true;
}
}
if (!hasValidChildren && ((textContent = XMLUtil.getTextContent(n)) != null)) {
sb.append(textContent);
}
sb.append("</").append(name).append(">");
}
return sb.toString();
}
}
Convert NodeList To Node Array
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Utils {
public static Node[] convertToArray(NodeList list)
{
int length = list.getLength();
Node[] copy = new Node[length];
for (int n = 0; n < length; ++n)
copy[n] = list.item(n);
return copy;
}
}
Copies the source tree into the specified place in a destination tree.
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import com.sun.org.apache.xerces.internal.dom.AttrImpl;
import com.sun.org.apache.xerces.internal.dom.DocumentImpl;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class Main {
/**
* Copies the source tree into the specified place in a destination
* tree. The source node and its children are appended as children
* of the destination node.
* <p>
* <em>Note:</em> This is an iterative implementation.
*/
public static void copyInto(Node src, Node dest) throws DOMException {
// get node factory
Document factory = dest.getOwnerDocument();
boolean domimpl = factory instanceof DocumentImpl;
// placement variables
Node start = src;
Node parent = src;
Node place = src;
// traverse source tree
while (place != null) {
// copy this node
Node node = null;
int type = place.getNodeType();
switch (type) {
case Node.CDATA_SECTION_NODE: {
node = factory.createCDATASection(place.getNodeValue());
break;
}
case Node.ruMENT_NODE: {
node = factory.createComment(place.getNodeValue());
break;
}
case Node.ELEMENT_NODE: {
Element element = factory.createElement(place.getNodeName());
node = element;
NamedNodeMap attrs = place.getAttributes();
int attrCount = attrs.getLength();
for (int i = 0; i < attrCount; i++) {
Attr attr = (Attr)attrs.item(i);
String attrName = attr.getNodeName();
String attrValue = attr.getNodeValue();
element.setAttribute(attrName, attrValue);
if (domimpl && !attr.getSpecified()) {
((AttrImpl)element.getAttributeNode(attrName)).setSpecified(false);
}
}
break;
}
case Node.ENTITY_REFERENCE_NODE: {
node = factory.createEntityReference(place.getNodeName());
break;
}
case Node.PROCESSING_INSTRUCTION_NODE: {
node = factory.createProcessingInstruction(place.getNodeName(),
place.getNodeValue());
break;
}
case Node.TEXT_NODE: {
node = factory.createTextNode(place.getNodeValue());
break;
}
default: {
throw new IllegalArgumentException("can"t copy node type, "+
type+" ("+
node.getNodeName()+")");
}
}
dest.appendChild(node);
// iterate over children
if (place.hasChildNodes()) {
parent = place;
place = place.getFirstChild();
dest = node;
}
// advance
else {
place = place.getNextSibling();
while (place == null && parent != start) {
place = parent.getNextSibling();
parent = parent.getParentNode();
dest = dest.getParentNode();
}
}
}
} // copyInto(Node,Node)
}
Create a new element and move the middle text node to it
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getDocumentElement();
Text text1 = (Text) element.getFirstChild();
String string = text1.getData();
String word = "some";
Text text2 = text1.splitText(string.indexOf(word));
Element newElement = doc.createElement("b");
newElement.appendChild(text2);
}
}
DOM helper for root element
/**
*
*/
//org.ajax4jsf.builder.xml;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* This class must read XML file from input stream and can extract body of root
* element for include into target in generation.
*
* @author shura
*
*/
public class XMLBody {
private Document xmlDocument;
private Element rootElement;
/**
* Load XML document and parse it into DOM.
*
* @param input
* @throws ParsingException
*/
public void loadXML(InputStream input) throws Exception {
try {
// Create Document Builder Factory
DocumentBuilderFactory docFactory = DocumentBuilderFactory
.newInstance();
docFactory.setValidating(false);
// Create Document Builder
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
docBuilder.isValidating();
// Disable loading of external Entityes
docBuilder.setEntityResolver(new EntityResolver() {
// Dummi resolver - alvays do nothing
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
return new InputSource(new StringReader(""));
}
});
// open and parse XML-file
xmlDocument = docBuilder.parse(input);
// Get Root xmlElement
rootElement = xmlDocument.getDocumentElement();
} catch (Exception e) {
throw new Exception("Error load XML ", e);
}
}
/**
* Check name of root element is as expected.
*
* @param name
* @return
*/
public boolean isRootName(String name) {
return rootElement.getNodeName().equals(name);
}
public String getDoctype() {
DocumentType doctype = xmlDocument.getDoctype();
if (null != doctype) {
return doctype.getName();
}
return null;
}
public String getPiblicId() {
DocumentType doctype = xmlDocument.getDoctype();
if (null != doctype) {
return doctype.getPublicId();
}
return null;
}
public String getRootTypeName() {
return rootElement.getSchemaTypeInfo().getTypeName();
}
public String getContent() throws Exception {
NodeList childNodes = rootElement.getChildNodes();
return serializeNodes(childNodes);
}
private String serializeNodes(NodeList childNodes) throws Exception {
DocumentFragment fragment = xmlDocument.createDocumentFragment();
for (int i = 0; i < childNodes.getLength(); i++) {
fragment.appendChild(childNodes.item(i).cloneNode(true));
}
try {
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty("omit-xml-declaration", "yes");
StringWriter out = new StringWriter();
StreamResult result = new StreamResult(out);
transformer.transform(new DOMSource(fragment), result);
return out.toString();
} catch (Exception e) {
throw new Exception(e);
}
}
public String getContent(String xpath) throws Exception{
XPath path = XPathFactory.newInstance().newXPath();
NodeList childNodes;
try {
childNodes = (NodeList) path.evaluate(xpath, xmlDocument,XPathConstants.NODESET);
} catch (XPathExpressionException e) {
throw new Exception("Error evaluate xpath",e);
}
return serializeNodes(childNodes);
}
}
Find the first text descendent node of an element
/*
* Copyright (C) 2001 Christian Cryder [christianc@granitepeaks.ru]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id: DOMUtil.java 114 2005-12-09 15:51:51Z christianc $
*/
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import org.w3c.dom.Attr;
import org.w3c.dom.CharacterData;
import org.w3c.dom.rument;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
/**
* DOM related utility functions.
*/
public class DOMUtil {
private static byte[] sep = System.getProperty("line.separator").getBytes();
/**
* Find the first text descendent node of an element.
* This recursively looks more than one level to search
* for text in font nodes, etc.
*
* @param node The starting node for the search.
* @return The text node or null if not found.
*/
public static Text findFirstText(Node node) {
if (node instanceof Text) return (Text) node;
for (Node child = node.getFirstChild(); child!=null; child = child.getNextSibling()) {
Text text = findFirstText(child);
if (text!=null) return text;
}
return null;
}
/**
* Gets the first text descendent node of an element.
* This recursively looks more than one level to search
* for text in font nodes, etc. Throws a DOMException
* if the Text object is not found.
*
* @param node The starting node for the search.
* @return The text node or null if not found.
* @throws DOMException if the Text object is not found
*/
public static Text getFirstText(Node node) {
Text text = findFirstText(node);
if (text==null) {
String msg = "No child text mode found for element";
String id = getID(node);
throw new DOMException((short) -1, msg+(id!=null ? "; id=\""+id+"\"" : ""));
}
return text;
}
/**
* Automatically set text in a Node. Basically we find the first
* Text node beneath the current node and replace it with a
* CDATASection for the incoming text. All other Text nodes are
* removed. Throws a DOMException if it"s illegal to add a Text
* child to the particular node.
*
* @param node the starting node for the search.
* @param text the text to be set
* @param allowMarkupInText whether to allow markup in text to pass through unparsed
* @return the updated node
* @throws DOMException if the Text object is not found
*/
public static Node setTextInNode(Node node, String text, boolean allowMarkupInText) {
//start by setting the value in the first text node we find with a comment
Comment comment = node.getOwnerDocument().createComment("");
Node newNode = null;
//csc_092701.1 - support both encoded/unencoded text
if (allowMarkupInText) newNode = node.getOwnerDocument().createCDATASection(text);
else newNode = node.getOwnerDocument().createTextNode(text);
//System.out.println ("newNode: "+newNode);
Text textComp = DOMUtil.findFirstText((Element) node);
//System.out.println ("textComp:"+textComp);
if (textComp==null) {
node.appendChild(comment);
} else {
Node parent = textComp.getParentNode();
parent.replaceChild(comment, textComp);
}
//now remove all the rest of the text nodes
removeAllTextNodes(node);
//now replace the comment with the newNode
Node parent = comment.getParentNode();
parent.replaceChild(newNode, comment);
//System.out.println ("parent: "+parent);
//System.out.println ("result: "+DOMUtil.findFirstText((Element) parent));
//DOMUtil.printStackTrace(parent.getOwnerDocument().getDocumentElement());
return node;
}
/**
* Remove all text nodes below this node
*
* @param node The starting node for the search.
*/
public static void removeAllTextNodes(Node node) {
if (node==null) return;
if (!node.hasChildNodes()) return;
NodeList nl = node.getChildNodes();
for (int i=nl.getLength()-1; i>=0; i--) {
Node n = (Node) nl.item(i);
if (n instanceof Text) node.removeChild(n);
else removeAllTextNodes(n);
}
}
/**
* Given a Node name, return the "id" attribute if it exists.
* If it does not exist, return null instead. This is basically
* just a convenience method to cast the node to element and
* return the id from that.
*
* @param node the node name in question
* @return the id value for the given node, if it exists. null if
* doesn"t
*/
public static String getID(Node node) {
return getID(node, null);
}
/**
* Given a Node, return the "id" attribute if it exists.
* If it does not exist, return nullResponse instead. This is basically
* just a convenience method to cast the node to element and
* return the id from that.
*
* @param node the node in question
* @param nullResponse the response to be returned if the id attribute
* does not exist
* @return the id value for the given node, if it exists. null if
* doesn"t
*/
public static String getID(Node node, String nullResponse) {
String nodeName = nullResponse;
if (node instanceof Element) {
nodeName = ((Element) node).getAttribute("id");
}
return nodeName;
}
protected static void print(OutputStream out, String s) {
if (out!=null) try {
out.write(s.getBytes());
out.write(sep);
} catch (IOException ioe) {}
}
}
Get the first text node associated with this element
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Utils {
/**
* Get the first text node associated with this element
* @param parent the node containing text
* @return Text (trimmed of leanding/trailing whitespace, null if none)
*/
public static String getFirstText(Node parent) {
return getTextNodeByNumber(parent, 1);
}
/**
* Get the specified text node associated with this element
* @param parent the node containing text
* @param number The text node to fetch (1st, 2nd, etc)
* @return Text (trimmed of leanding/trailing whitespace, null if none)
*/
public static String getTextNodeByNumber(Node parent, int number) {
String text = null;
int count = 1;
if (parent != null) {
for (Node child = parent.getFirstChild();
child != null;
child = child.getNextSibling()) {
if ((child.getNodeType() == Node.TEXT_NODE) && (count++ == number)) {
text = child.getNodeValue();
return text.trim();
}
}
}
return text;
}
}
Get the text node
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getDocumentElement();
Text text1 = (Text) element.getFirstChild();
String string = text1.getData();
}
}
Move all children of the element in front of the element
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = (Element) doc.getElementsByTagName("b").item(0);
Node parent = element.getParentNode();
while (element.hasChildNodes()) {
parent.insertBefore(element.getFirstChild(), element);
}
}
}
Remove All nodes
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
removeAll(doc, Node.ELEMENT_NODE, "junk");
removeAll(doc, Node.ruMENT_NODE, null);
doc.normalize();
}
public static void removeAll(Node node, short nodeType, String name) {
if (node.getNodeType() == nodeType && (name == null || node.getNodeName().equals(name))) {
node.getParentNode().removeChild(node);
} else {
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
removeAll(list.item(i), nodeType, name);
}
}
}
}
Remove this node from its parent.
/**********************************************************************************
*
* Copyright (c) 2003, 2004 The Regents of the University of Michigan, Trustees of Indiana University,
* Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation
*
* Licensed under the Educational Community License Version 1.0 (the "License");
* By obtaining, using and/or copying this Original Work, you agree that you have read,
* understand, and will comply with the terms and conditions of the Educational Community License.
* You may obtain a copy of the License at:
*
* http://cvs.sakaiproject.org/licenses/license_1_0.html
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**********************************************************************************/
import org.w3c.dom.Node;
public class Utils {
/**
* Remove this node from its parent.
* @param node the node to remove
* @return Node removed
*/
public Node removeNode(Node node) {
return node.getParentNode().removeChild(node);
}
}
Removing a Node from a DOM Document
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = (Element) doc.getElementsByTagName("junk").item(0);
element.getParentNode().removeChild(element);
}
}
Returns a first child DOM Node of type ELEMENT_NODE for the specified Node
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.w3c.dom.Node;
public final class NodeUtils {
/**
* Returns a first child DOM Node of type ELEMENT_NODE
* for the specified Node.
*/
public static Node getChildElementNode(Node xmlNode) {
if (xmlNode == null || !xmlNode.hasChildNodes()) {
return null;
}
xmlNode = xmlNode.getFirstChild();
while (xmlNode != null
&& xmlNode.getNodeType() != Node.ELEMENT_NODE) {
xmlNode = xmlNode.getNextSibling();
}
return xmlNode;
}
}
Returns a list of value for the given node
/**
* EasyBeans
* Copyright (C) 2006 Bull S.A.S.
* Contact: easybeans@ow2.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* --------------------------------------------------------------------------
* $Id: XMLUtils.java 2049 2007-11-20 14:32:56Z benoitf $
* --------------------------------------------------------------------------
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Class with some useful methods on XML document.
*/
public final class XMLUtils {
/**
* Returns a list of value for the given node.
* @param ns the namespace.
* @param base the element from where to search.
* @param name of the element to get.
* @return the list of value of this element.
*/
public static List<String> getStringListValueElement(final String ns, final Element base, final String name) {
List<String> returnedlist = new ArrayList<String>();
// Get element
NodeList list = base.getElementsByTagNameNS(ns, name);
int length = list.getLength();
// Get all values of all elements
if (length > 0) {
for (int i = 0; i < length; i++) {
Element element = (Element) list.item(i);
Node node = element.getFirstChild();
if (node != null) {
returnedlist.add(node.getNodeValue());
}
}
}
return returnedlist;
}
}
Returns the value of the child node with the given name
/**
* EasyBeans
* Copyright (C) 2006 Bull S.A.S.
* Contact: easybeans@ow2.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* --------------------------------------------------------------------------
* $Id: XMLUtils.java 2049 2007-11-20 14:32:56Z benoitf $
* --------------------------------------------------------------------------
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Class with some useful methods on XML document.
*/
public final class XMLUtils {
/**
* Returns the value of the child node with the given name.
* @param base the element from where to search.
* @param name of the element to get.
* @return the value of this element.
*/
public static String getChildStringValueForElement(final Element base, final String name) {
String value = null;
NodeList nodeList = base.getChildNodes();
if (nodeList.getLength() > 0) {
int length = nodeList.getLength();
for (int i = 0; i < length; i++) {
Node node = nodeList.item(i);
// Get an element, create an instance of the element
if (Node.ELEMENT_NODE == node.getNodeType()) {
if (name.equals(node.getNodeName())) {
// Get value of this child
Node elNode = ((Element) node).getFirstChild();
if (elNode != null) {
value = elNode.getNodeValue();
break;
}
}
}
}
}
return value;
}
}
Search earlier siblings for a given node
/**********************************************************************************
*
* Copyright (c) 2003, 2004 The Regents of the University of Michigan, Trustees of Indiana University,
* Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation
*
* Licensed under the Educational Community License Version 1.0 (the "License");
* By obtaining, using and/or copying this Original Work, you agree that you have read,
* understand, and will comply with the terms and conditions of the Educational Community License.
* You may obtain a copy of the License at:
*
* http://cvs.sakaiproject.org/licenses/license_1_0.html
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**********************************************************************************/
import org.w3c.dom.Node;
public class Utils {
/**
* Search earlier siblings for a given node
* @param currentNode Starting point for our search
* @param tagName Node name to look up
* @return matching Node (null if none)
*/
public static Node getPreviousSiblingByName(Node currentNode, String tagName) {
Node node = currentNode.getPreviousSibling();
while ((node != null) && (!node.getNodeName().equals(tagName))) {
node = node.getPreviousSibling();
}
return node;
}
}
Search our next siblings for a given node
/**********************************************************************************
*
* Copyright (c) 2003, 2004 The Regents of the University of Michigan, Trustees of Indiana University,
* Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation
*
* Licensed under the Educational Community License Version 1.0 (the "License");
* By obtaining, using and/or copying this Original Work, you agree that you have read,
* understand, and will comply with the terms and conditions of the Educational Community License.
* You may obtain a copy of the License at:
*
* http://cvs.sakaiproject.org/licenses/license_1_0.html
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**********************************************************************************/
import org.w3c.dom.Node;
public class Utils {
/**
* Search our next siblings for a given node
* @param currentNode Starting point for our search
* @param tagName Node name to look up
* @return matching Node (null if none)
*/
public static Node getNextSiblingByName(Node currentNode, String tagName) {
Node node = currentNode.getNextSibling();
while ((node != null) && (!node.getNodeName().equals(tagName))) {
node = node.getNextSibling();
}
return node;
}
}
Search up the tree for a given node
/**********************************************************************************
*
* Copyright (c) 2003, 2004 The Regents of the University of Michigan, Trustees of Indiana University,
* Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation
*
* Licensed under the Educational Community License Version 1.0 (the "License");
* By obtaining, using and/or copying this Original Work, you agree that you have read,
* understand, and will comply with the terms and conditions of the Educational Community License.
* You may obtain a copy of the License at:
*
* http://cvs.sakaiproject.org/licenses/license_1_0.html
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**********************************************************************************/
import org.w3c.dom.Node;
public class Utils {
/**
* Search up the tree for a given node
* @param currentNode Starting point for our search
* @param tagName Node name to look up
* @return matching Node (null if none)
*/
public static Node getPreviousNodeByName(Node currentNode, String tagName) {
Node node = currentNode.getParentNode();
while ((node != null) && (!node.getNodeName().equals(tagName))) {
node = node.getParentNode();
}
return node;
}
}
Simplified implementation of a Node from a Document Object Model (DOM)
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
/**
* Simplified implementation of a Node from a Document Object Model (DOM)
* parse of an XML document. This class is used to represent a DOM tree
* so that the XML parser"s implementation of <code>org.w3c.dom</code> need
* not be visible to the remainder of Jasper.
* <p>
* <strong>WARNING</strong> - Construction of a new tree, or modifications
* to an existing one, are not thread-safe and such accesses must be
* synchronized.
*
* @author Craig R. McClanahan
* @version $Revision: 515 $ $Date: 2008-03-17 22:02:23 +0100 (Mon, 17 Mar 2008) $
*/
public class TreeNode {
// ----------------------------------------------------------- Constructors
/**
* Construct a new node with no parent.
*
* @param name The name of this node
*/
public TreeNode(String name) {
this(name, null);
}
/**
* Construct a new node with the specified parent.
*
* @param name The name of this node
* @param parent The node that is the parent of this node
*/
public TreeNode(String name, TreeNode parent) {
super();
this.name = name;
this.parent = parent;
if (this.parent != null)
this.parent.addChild(this);
}
// ----------------------------------------------------- Instance Variables
/**
* The attributes of this node, keyed by attribute name,
* Instantiated only if required.
*/
protected HashMap attributes = null;
/**
* The body text associated with this node (if any).
*/
protected String body = null;
/**
* The children of this node, instantiated only if required.
*/
protected ArrayList children = null;
/**
* The name of this node.
*/
protected String name = null;
/**
* The parent node of this node.
*/
protected TreeNode parent = null;
// --------------------------------------------------------- Public Methods
/**
* Add an attribute to this node, replacing any existing attribute
* with the same name.
*
* @param name The attribute name to add
* @param value The new attribute value
*/
public void addAttribute(String name, String value) {
if (attributes == null)
attributes = new HashMap();
attributes.put(name, value);
}
/**
* Add a new child node to this node.
*
* @param node The new child node
*/
public void addChild(TreeNode node) {
if (children == null)
children = new ArrayList();
children.add(node);
}
/**
* Return the value of the specified node attribute if it exists, or
* <code>null</code> otherwise.
*
* @param name Name of the requested attribute
*/
public String findAttribute(String name) {
if (attributes == null)
return (null);
else
return ((String) attributes.get(name));
}
/**
* Return an Iterator of the attribute names of this node. If there are
* no attributes, an empty Iterator is returned.
*/
public Iterator findAttributes() {
if (attributes == null)
return (Collections.EMPTY_LIST.iterator());
else
return (attributes.keySet().iterator());
}
/**
* Return the first child node of this node with the specified name,
* if there is one; otherwise, return <code>null</code>.
*
* @param name Name of the desired child element
*/
public TreeNode findChild(String name) {
if (children == null)
return (null);
Iterator items = children.iterator();
while (items.hasNext()) {
TreeNode item = (TreeNode) items.next();
if (name.equals(item.getName()))
return (item);
}
return (null);
}
/**
* Return an Iterator of all children of this node. If there are no
* children, an empty Iterator is returned.
*/
public Iterator findChildren() {
if (children == null)
return (Collections.EMPTY_LIST.iterator());
else
return (children.iterator());
}
/**
* Return an Iterator over all children of this node that have the
* specified name. If there are no such children, an empty Iterator
* is returned.
*
* @param name Name used to select children
*/
public Iterator findChildren(String name) {
if (children == null)
return (Collections.EMPTY_LIST.iterator());
ArrayList results = new ArrayList();
Iterator items = children.iterator();
while (items.hasNext()) {
TreeNode item = (TreeNode) items.next();
if (name.equals(item.getName()))
results.add(item);
}
return (results.iterator());
}
/**
* Return the body text associated with this node (if any).
*/
public String getBody() {
return (this.body);
}
/**
* Return the name of this node.
*/
public String getName() {
return (this.name);
}
/**
* Remove any existing value for the specified attribute name.
*
* @param name The attribute name to remove
*/
public void removeAttribute(String name) {
if (attributes != null)
attributes.remove(name);
}
/**
* Remove a child node from this node, if it is one.
*
* @param node The child node to remove
*/
public void removeNode(TreeNode node) {
if (children != null)
children.remove(node);
}
/**
* Set the body text associated with this node (if any).
*
* @param body The body text (if any)
*/
public void setBody(String body) {
this.body = body;
}
/**
* Return a String representation of this TreeNode.
*/
public String toString() {
StringBuffer sb = new StringBuffer();
toString(sb, 0, this);
return (sb.toString());
}
// ------------------------------------------------------ Protected Methods
/**
* Append to the specified StringBuffer a character representation of
* this node, with the specified amount of indentation.
*
* @param sb The StringBuffer to append to
* @param indent Number of characters of indentation
* @param node The TreeNode to be printed
*/
protected void toString(StringBuffer sb, int indent,
TreeNode node) {
int indent2 = indent + 2;
// Reconstruct an opening node
for (int i = 0; i < indent; i++)
sb.append(" ");
sb.append("<");
sb.append(node.getName());
Iterator names = node.findAttributes();
while (names.hasNext()) {
sb.append(" ");
String name = (String) names.next();
sb.append(name);
sb.append("=\"");
String value = node.findAttribute(name);
sb.append(value);
sb.append("\"");
}
sb.append(">\n");
// Reconstruct the body text of this node (if any)
String body = node.getBody();
if ((body != null) && (body.length() > 0)) {
for (int i = 0; i < indent2; i++)
sb.append(" ");
sb.append(body);
sb.append("\n");
}
// Reconstruct child nodes with extra indentation
Iterator children = node.findChildren();
while (children.hasNext()) {
TreeNode child = (TreeNode) children.next();
toString(sb, indent2, child);
}
// Reconstruct a closing node marker
for (int i = 0; i < indent; i++)
sb.append(" ");
sb.append("</");
sb.append(node.getName());
sb.append(">\n");
}
}
Split the node at the beginning of the word
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class Main {
public static void main(String[] argv) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(new File("filename"));
Element element = doc.getDocumentElement();
Text text1 = (Text) element.getFirstChild();
String string = text1.getData();
String word = "some";
Text text2 = text1.splitText(string.indexOf(word));
}
}