Java Tutorial/XML/DOM Element
Содержание
- 1 Add an entity to a specified Element.
- 2 Add a new element to the given parent
- 3 Add Text object to an Element.
- 4 Build a QName from the element name
- 5 Copy an XML document
- 6 Create a new element
- 7 Create Empty DOM Document
- 8 Create New Element And Set Attribute
- 9 Document To String
- 10 Find All Elements By Tag Name Name Space
- 11 Find Element And Set Or Create And Set
- 12 Find Element Or Container
- 13 Finds and returns the first child element node.
- 14 Finds and returns the first child node with the given name and attribute name, value pair.
- 15 Finds and returns the last child element node.
- 16 Finds and returns the last child node with the given name and attribute name, value pair.
- 17 Finds and returns the next sibling element node.
- 18 Finds and returns the next sibling node with the given name and attribute name, value pair.
- 19 Get Element Boolean Value
- 20 Get Element Date Value
- 21 Get Element Float Value
- 22 Get Element Int Value
- 23 Get Element Long Value
- 24 Get Element QName
- 25 Get Elements by parent element
- 26 Get Element String Value
- 27 Get Element Text
- 28 Get First Element
- 29 Get Next Element
- 30 Get the first element child.
- 31 Get the name of this element
- 32 Get the next sibling with the same name and type
- 33 Moves the content of the given element to the given element
- 34 Return child elements with specified name.
- 35 Returns an iterator over the children of the given element with the given tag name.
- 36 Returns the concatenated child text of the specified node.
- 37 Returns the text of the element
- 38 Return the first element child with the specified qualified name.
- 39 Return the first named Element found. Null if none.
- 40 Return the next sibling with a given name and type
Add an entity to a specified Element.
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Utils {
/**
* Add an entity to a specified Element.
* (eg <code>DomUtils.addEntity(element, "nbsp");</code>)
* @param element the containing element
* @param entity the entity to add
*/
public static void addEntity(Element element, String entity) {
element.appendChild(element.getOwnerDocument().createEntityReference(entity));
}
}
Add a new element to the given parent
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Utils {
/**
* Add a new element to the given parent
* @param parent the parent Element
* @param name the child name
* @return new Element
*/
public static Element createElement(Element parent, String name) {
Document document;
Element element;
document = parent.getOwnerDocument();
element = document.createElement(name);
parent.appendChild(element);
return element;
}
}
Add Text object to an Element.
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Utils {
/**
* Add Text object to an Element.
* @param element the containing element
* @param text the text to add
*/
public static void addText(Element element, String text) {
element.appendChild(element.getOwnerDocument().createTextNode(text));
}
}
Build a QName from the element name
import javax.xml.namespace.QName;
import org.w3c.dom.Element;
public class Utils {
/**
* Build a QName from the element name
* @param el
* @return
*/
public static QName getQName(Element el) {
if (el == null) {
return null;
} else if (el.getPrefix() != null) {
return new QName(el.getNamespaceURI(), el.getLocalName(), el.getPrefix());
} else {
return new QName(el.getNamespaceURI(), el.getLocalName());
}
}
}
Copy an XML document
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Utils {
/**
* Copy an XML document, adding it as a child of the target document root
* @param source Document to copy
* @param target Document to contain copy
*/
public static void copyDocument(Document source, Document target)
{
Node node = target.importNode(source.getDocumentElement(), true);
target.getDocumentElement().appendChild(node);
}
}
Create a new element
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Utils {
/**
* Create a new element
* @param document Document to contain the new element
* @param name the element name
* @return new Element
*/
public static Element createElement(Document document, String name) {
Element element;
return document.createElement(name);
}
}
Create Empty DOM Document
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
/*******************************************************************************
* Copyright (C) 2007 Google Inc.
*
* Licensed 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.
******************************************************************************/
/**
* Various XML utilities.
*
* @author simonjsmith, ksim
* @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
* @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
* manipulation
*/
public class Utils {
public static Document newEmptyDocument() {
DocumentBuilderFactory factory = null;
DocumentBuilder builder = null;
Document ret;
try {
factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
ret = builder.newDocument();
return ret;
}
}
Create New Element And Set Attribute
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/*******************************************************************************
* Copyright (C) 2007 Google Inc.
*
* Licensed 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.
******************************************************************************/
/**
* Various XML utilities.
*
* @author simonjsmith, ksim
* @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
* @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
* manipulation
*/
public class Utils {
public static Element createNewElementAndSetAndAttribute(Document document,
Element parent, String childElement, String childValue,
String attributeName, String attributeValue) {
Element child = createNewElementAndSet(document, parent, childElement,
childValue);
child.setAttribute(attributeName, attributeValue);
return child;
}
public static Element createNewElementAndSet(Document document,
Element parent, String childElement, String childValue) {
Element child = (Element) document.createElement(childElement);
parent.appendChild(child);
child.setNodeValue(childValue);
child.appendChild(document.createTextNode(childValue));
return child;
}
}
Document To String
/*
* Copyright 2003-2008 The Apache Software Foundation.
*
* Licensed 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.io.ByteArrayOutputStream;
import java.io.OutputStream;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
public static void ElementToStream(Element element, OutputStream out) {
try {
DOMSource source = new DOMSource(element);
StreamResult result = new StreamResult(out);
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
transformer.transform(source, result);
} catch (Exception ex) {
}
}
public static String DocumentToString(Document doc) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ElementToStream(doc.getDocumentElement(), baos);
return new String(baos.toByteArray());
}
}
Find All Elements By Tag Name Name Space
/**
* 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.LinkedList;
import java.util.List;
import javax.xml.namespace.QName;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Few simple utils to read DOM. This is originally from the Jakarta Commons
* Modeler.
*
* @author Costin Manolache
*/
public class Utils {
public static List<Element> findAllElementsByTagNameNS(Element elem, String nameSpaceURI,
String localName) {
List<Element> ret = new LinkedList<Element>();
findAllElementsByTagNameNS(elem, nameSpaceURI, localName, ret);
return ret;
}
private static void findAllElementsByTagName(Element el, String tagName, List<Element> elementList) {
if (tagName.equals(el.getTagName())) {
elementList.add(el);
}
Element elem = getFirstElement(el);
while (elem != null) {
findAllElementsByTagName(elem, tagName, elementList);
elem = getNextElement(elem);
}
}
private static void findAllElementsByTagNameNS(Element el, String nameSpaceURI, String localName,
List<Element> elementList) {
if (localName.equals(el.getLocalName()) && nameSpaceURI.contains(el.getNamespaceURI())) {
elementList.add(el);
}
Element elem = getFirstElement(el);
while (elem != null) {
findAllElementsByTagNameNS(elem, nameSpaceURI, localName, elementList);
elem = getNextElement(elem);
}
}
public static Element getFirstElement(Node parent) {
Node n = parent.getFirstChild();
while (n != null && Node.ELEMENT_NODE != n.getNodeType()) {
n = n.getNextSibling();
}
if (n == null) {
return null;
}
return (Element) n;
}
public static Element getNextElement(Element el) {
Node nd = el.getNextSibling();
while (nd != null) {
if (nd.getNodeType() == Node.ELEMENT_NODE) {
return (Element) nd;
}
nd = nd.getNextSibling();
}
return null;
}
}
Find Element And Set Or Create And Set
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/*******************************************************************************
* Copyright (C) 2007 Google Inc.
*
* Licensed 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.
******************************************************************************/
/**
* Various XML utilities.
*
* @author simonjsmith, ksim
* @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
* @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
* manipulation
*/
public class Utils {
public static Element findElementAndSetElseCreateAndSet(Document document,
Element parent, String child, boolean value) {
return findElementAndSetElseCreateAndSet(document, parent, child, ""
+ value);
}
public static Element findElementAndSetElseCreateAndSet(Document document,
Element parent, String child, float value) {
return findElementAndSetElseCreateAndSet(document, parent, child, ""
+ value);
}
public static Element findElementAndSetElseCreateAndSet(Document document,
Element parent, String element, Date date) {
return findElementAndSetElseCreateAndSet(document, parent, element,
getDateString(date));
}
public static Element findElementAndSetElseCreateAndSet(Document document,
Element parent, String child, String value) {
NodeList nl = parent.getElementsByTagName(child);
if (nl.getLength() == 0) {
parent.appendChild(document.createElement(child));
}
Element ret = (Element) parent.getElementsByTagName(child).item(0);
if (ret.getFirstChild() != null) {
ret.removeChild(ret.getFirstChild());
}
ret.appendChild(document.createTextNode(value));
return ret;
}
}
Find Element Or Container
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/*******************************************************************************
* Copyright (C) 2007 Google Inc.
*
* Licensed 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.
******************************************************************************/
/**
* Various XML utilities.
*
* @author simonjsmith, ksim
* @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
* @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
* manipulation
*/
public class Utils {
public static Element findElementOrContainer(Document document,
Element parent, String element) {
NodeList nl = parent.getElementsByTagName(element);
if (nl.getLength() == 0) {
return null;
}
return (Element) nl.item(0);
}
}
Finds and returns the first child element node.
import org.w3c.dom.Element;
import org.w3c.dom.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.
*/
public class Main {
/** Finds and returns the first child element node. */
public static Element getFirstChildElement(Node parent) {
// search for node
Node child = parent.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
return (Element)child;
}
child = child.getNextSibling();
}
// not found
return null;
} // getFirstChildElement(Node):Element
}
Finds and returns the first child node with the given name and attribute name, value pair.
import org.w3c.dom.Element;
import org.w3c.dom.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.
*/
public class Main {
/**
* Finds and returns the first child node with the given name and
* attribute name, value pair.
*/
public static Element getFirstChildElement(Node parent,
String elemName,
String attrName,
String attrValue) {
// search for node
Node child = parent.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element)child;
if (element.getNodeName().equals(elemName) &&
element.getAttribute(attrName).equals(attrValue)) {
return element;
}
}
child = child.getNextSibling();
}
// not found
return null;
} // getFirstChildElement(Node,String,String,String):Element
}
Finds and returns the last child element node.
import org.w3c.dom.Element;
import org.w3c.dom.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.
*/
public class Main {
/** Finds and returns the last child element node.
* Overload previous method for non-Xerces node impl.
*/
public static Element getLastChildElement(Node parent) {
// search for node
Node child = parent.getLastChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
return (Element)child;
}
child = child.getPreviousSibling();
}
// not found
return null;
} // getLastChildElement(Node):Element
}
Finds and returns the last child node with the given name and attribute name, value pair.
import org.w3c.dom.Element;
import org.w3c.dom.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.
*/
public class Main {
/**
* Finds and returns the last child node with the given name and
* attribute name, value pair.
*/
public static Element getLastChildElement(Node parent,
String elemName,
String attrName,
String attrValue) {
// search for node
Node child = parent.getLastChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element)child;
if (element.getNodeName().equals(elemName) &&
element.getAttribute(attrName).equals(attrValue)) {
return element;
}
}
child = child.getPreviousSibling();
}
// not found
return null;
} // getLastChildElement(Node,String,String,String):Element
}
Finds and returns the next sibling element node.
import org.w3c.dom.Element;
import org.w3c.dom.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.
*/
public class Main {
/** Finds and returns the next sibling element node. */
public static Element getNextSiblingElement(Node node) {
// search for node
Node sibling = node.getNextSibling();
while (sibling != null) {
if (sibling.getNodeType() == Node.ELEMENT_NODE) {
return (Element)sibling;
}
sibling = sibling.getNextSibling();
}
// not found
return null;
} // getNextSiblingElement(Node):Element
}
Finds and returns the next sibling node with the given name and attribute name, value pair.
import org.w3c.dom.Element;
import org.w3c.dom.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.
*/
public class Main {
/**
* Finds and returns the next sibling node with the given name and
* attribute name, value pair. Since only elements have attributes,
* the node returned will be of type Node.ELEMENT_NODE.
*/
public static Element getNextSiblingElement(Node node,
String elemName,
String attrName,
String attrValue) {
// search for node
Node sibling = node.getNextSibling();
while (sibling != null) {
if (sibling.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element)sibling;
if (element.getNodeName().equals(elemName) &&
element.getAttribute(attrName).equals(attrValue)) {
return element;
}
}
sibling = sibling.getNextSibling();
}
// not found
return null;
} // getNextSiblingElement(Node,String,String,String):Element
}
Get Element Boolean Value
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*******************************************************************************
* Copyright (C) 2007 Google Inc.
*
* Licensed 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.
******************************************************************************/
/**
* Various XML utilities.
*
* @author simonjsmith, ksim
* @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
* @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
* manipulation
*/
public class Utils {
public static boolean getElementBooleanValue(Document document,
Element parent, String element) {
return Boolean
.valueOf(getElementStringValue(document, parent, element))
.booleanValue();
}
public static String getElementStringValue(Document document,
Element parent, String element) {
NodeList nl = parent.getElementsByTagName(element);
if (nl.getLength() == 0) {
return "";
}
Node n = nl.item(0).getFirstChild();
if (n == null) {
return "";
}
return n.getNodeValue();
}
}
Get Element Date Value
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*******************************************************************************
* Copyright (C) 2007 Google Inc.
*
* Licensed 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.
******************************************************************************/
/**
* Various XML utilities.
*
* @author simonjsmith, ksim
* @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
* @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
* manipulation
*/
public class Utils {
public static Date getElementDateValue(Document document, Element parent, String string) {
return parseDate(getElementStringValue(document, parent, string));
}
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"T"HH:mm:ss");
public static Date parseDate(String date) {
try {
return sdf.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static String getElementStringValue(Document document, Element parent, String element) {
NodeList nl = parent.getElementsByTagName(element);
if (nl.getLength() == 0) {
return "";
}
Node n = nl.item(0).getFirstChild();
if (n == null) {
return "";
}
return n.getNodeValue();
}
}
Get Element Float Value
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*******************************************************************************
* Copyright (C) 2007 Google Inc.
*
* Licensed 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.
******************************************************************************/
/**
* Various XML utilities.
*
* @author simonjsmith, ksim
* @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
* @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
* manipulation
*/
public class Utils {
public static float getElementFloatValue(Document document, Element parent,
String element) {
return Float
.parseFloat(getElementStringValue(document, parent, element));
}
public static String getElementStringValue(Document document,
Element parent, String element) {
NodeList nl = parent.getElementsByTagName(element);
if (nl.getLength() == 0) {
return "";
}
Node n = nl.item(0).getFirstChild();
if (n == null) {
return "";
}
return n.getNodeValue();
}
}
Get Element Int Value
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*******************************************************************************
* Copyright (C) 2007 Google Inc.
*
* Licensed 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.
******************************************************************************/
/**
* Various XML utilities.
*
* @author simonjsmith, ksim
* @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
* @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
* manipulation
*/
public class Utils {
public static int getElementIntValue(Document document, Element parent,
String string) {
return Integer
.parseInt(getElementStringValue(document, parent, string));
}
public static String getElementStringValue(Document document, Element parent, String element) {
NodeList nl = parent.getElementsByTagName(element);
if (nl.getLength() == 0) {
return "";
}
Node n = nl.item(0).getFirstChild();
if (n == null) {
return "";
}
return n.getNodeValue();
}
}
Get Element Long Value
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*******************************************************************************
* Copyright (C) 2007 Google Inc.
*
* Licensed 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.
******************************************************************************/
/**
* Various XML utilities.
*
* @author simonjsmith, ksim
* @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
* @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
* manipulation
*/
public class Utils {
public static long getElementLongValue(Document document, Element parent,
String string) {
return Long.parseLong(getElementStringValue(document, parent, string));
}
public static String getElementStringValue(Document document, Element parent, String element) {
NodeList nl = parent.getElementsByTagName(element);
if (nl.getLength() == 0) {
return "";
}
Node n = nl.item(0).getFirstChild();
if (n == null) {
return "";
}
return n.getNodeValue();
}
}
Get Element QName
/**
* 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 javax.xml.namespace.QName;
import org.w3c.dom.Element;
/**
* Few simple utils to read DOM. This is originally from the Jakarta Commons
* Modeler.
*
* @author Costin Manolache
*/
public class Utils {
public static QName getElementQName(Element el) {
return new QName(el.getNamespaceURI(), el.getLocalName());
}
}
Get Elements by parent element
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*******************************************************************************
* Copyright (C) 2007 Google Inc.
*
* Licensed 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.
******************************************************************************/
/**
* Various XML utilities.
*
* @author simonjsmith, ksim
* @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
* @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
* manipulation
*/
public class Utils {
public static Element[] getElements(Document document, Element parent) {
if (parent == null) {
return new Element[] {};
}
NodeList nl = parent.getChildNodes();
ArrayList al = new ArrayList();
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n instanceof Element) {
al.add((Element) nl.item(i));
}
}
Element[] ret = new Element[al.size()];
Iterator it = al.iterator();
int i = 0;
while (it.hasNext()) {
ret[i] = (Element) it.next();
i++;
}
return ret;
}
}
Get Element String Value
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*******************************************************************************
* Copyright (C) 2007 Google Inc.
*
* Licensed 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.
******************************************************************************/
/**
* Various XML utilities.
*
* @author simonjsmith, ksim
* @version 1.1 - ksim - March 6th, 2007 - Added functions regarding streaming
* @version 1.2 - ksim - March 10th, 2007 - Added functions regarding DOM
* manipulation
*/
public class Utils {
public static String getElementStringValue(Document document,
Element parent, String element) {
NodeList nl = parent.getElementsByTagName(element);
if (nl.getLength() == 0) {
return "";
}
Node n = nl.item(0).getFirstChild();
if (n == null) {
return "";
}
return n.getNodeValue();
}
}
Get Element Text
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Utils {
public static String getElementText(Element e) {
StringBuffer buf = new StringBuffer();
for (Node n = e.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n.getNodeType() == Node.TEXT_NODE || n.getNodeType() == Node.CDATA_SECTION_NODE) {
buf.append(n.getNodeValue());
}
}
return buf.toString();
}
}
Get First Element
/**
* 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 javax.xml.namespace.QName;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Few simple utils to read DOM. This is originally from the Jakarta Commons
* Modeler.
*
* @author Costin Manolache
*/
public class Utils {
public static Element getFirstElement(Node parent) {
Node n = parent.getFirstChild();
while (n != null && Node.ELEMENT_NODE != n.getNodeType()) {
n = n.getNextSibling();
}
if (n == null) {
return null;
}
return (Element)n;
}
public static Element getNextElement(Element el) {
Node nd = el.getNextSibling();
while (nd != null) {
if (nd.getNodeType() == Node.ELEMENT_NODE) {
return (Element)nd;
}
nd = nd.getNextSibling();
}
return null;
}
}
Get Next Element
/**
* 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 javax.xml.namespace.QName;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Few simple utils to read DOM. This is originally from the Jakarta Commons
* Modeler.
*
* @author Costin Manolache
*/
public class Utils {
public static Element getNextElement(Element el) {
Node nd = el.getNextSibling();
while (nd != null) {
if (nd.getNodeType() == Node.ELEMENT_NODE) {
return (Element)nd;
}
nd = nd.getNextSibling();
}
return null;
}
}
Get the first element child.
/**
* 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.io.OutputStream;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Node;
/**
* Few simple utils to read DOM. This is originally from the Jakarta Commons
* Modeler.
*
* @author Costin Manolache
*/
public class Utils {
/**
* Get the first element child.
*
* @param parent lookup direct childs
* @param name name of the element. If null return the first element.
*/
public static Node getChild(Node parent, String name) {
if (parent == null) {
return null;
}
Node first = parent.getFirstChild();
if (first == null) {
return null;
}
for (Node node = first; node != null; node = node.getNextSibling()) {
// System.out.println("getNode: " + name + " " +
// node.getNodeName());
if (node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
if (name != null && name.equals(node.getNodeName())) {
return node;
}
if (name == null) {
return node;
}
}
return null;
}
}
Get the name of this element
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Main {
// return the name of this element
public static String getName(Node node) {
return node.getNodeName();
} // getLocalName(Element): String
}
Get the next sibling with the same name and type
import org.w3c.dom.Node;
public class Main {
/** Get the next sibling with the same name and type
*/
public static Node getNext( Node current ) {
String name=current.getNodeName();
int type=current.getNodeType();
return getNext( current, name, type);
}
/**
*/
public static Node getNext( Node current, String name, int type) {
Node first=current.getNextSibling();
if( first==null ) return null;
for (Node node = first; node != null;
node = node.getNextSibling()) {
if( type >= 0 && node.getNodeType() != type ) continue;
//System.out.println("getNode: " + name + " " + node.getNodeName());
if( name==null )
return node;
if( name.equals( node.getNodeName() ) ) {
return node;
}
}
return null;
}
}
Moves the content of the given element to the given element
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Utils {
/**
*
*/
public static void moveContent(Element from, Element to) {
// lets move the child nodes across
NodeList childNodes = from.getChildNodes();
while (childNodes.getLength() > 0) {
Node node = childNodes.item(0);
from.removeChild(node);
to.appendChild(node);
}
}
}
Return child elements with specified name.
/**
* 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.Element;
import org.w3c.dom.Node;
/**
* Few simple utils to read DOM. This is originally from the Jakarta Commons
* Modeler.
*
* @author Costin Manolache
*/
public class Utils {
/**
* Return child elements with specified name.
*
* @param parent
* @param ns
* @param localName
* @return
*/
public static List<Element> getChildrenWithName(Element parent, String ns, String localName) {
List<Element> r = new ArrayList<Element>();
for (Node n = parent.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n instanceof Element) {
Element e = (Element) n;
String eNs = (e.getNamespaceURI() == null) ? "" : e.getNamespaceURI();
if (ns.equals(eNs) && localName.equals(e.getLocalName())) {
r.add(e);
}
}
}
return r;
}
}
Returns an iterator over the children of the given element with the given tag name.
import java.util.ArrayList;
import java.util.Iterator;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
public class Utils {
/**
* Returns an iterator over the children of the given element with
* the given tag name.
*
* @param element The parent element
* @param tagName The name of the desired child
* @return An interator of children or null if element is null.
*/
public static Iterator<Element> getChildrenByTagName(Element element,
String tagName)
{
if (element == null) return null;
// getElementsByTagName gives the corresponding elements in the whole
// descendance. We want only children
NodeList children = element.getChildNodes();
ArrayList<Element> goodChildren = new ArrayList<Element>();
for (int i=0; i<children.getLength(); i++) {
Node currentChild = children.item(i);
if (currentChild.getNodeType() == Node.ELEMENT_NODE &&
((Element)currentChild).getTagName().equals(tagName)) {
goodChildren.add((Element)currentChild);
}
}
return goodChildren.iterator();
}
}
Returns the concatenated child text of the specified node.
import org.w3c.dom.Element;
import org.w3c.dom.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.
*/
public class Main {
/**
* Returns the concatenated child text of the specified node.
* This method only looks at the immediate children of type
* <code>Node.TEXT_NODE</code> or the children of any child
* node that is of type <code>Node.CDATA_SECTION_NODE</code>
* for the concatenation.
*
* @param node The node to look at.
*/
public static String getChildText(Node node) {
// is there anything to do?
if (node == null) {
return null;
}
// concatenate children text
StringBuffer str = new StringBuffer();
Node child = node.getFirstChild();
while (child != null) {
short type = child.getNodeType();
if (type == Node.TEXT_NODE) {
str.append(child.getNodeValue());
}
else if (type == Node.CDATA_SECTION_NODE) {
str.append(getChildText(child));
}
child = child.getNextSibling();
}
// return text value
return str.toString();
} // getChildText(Node):String
}
Returns the text of the element
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Utils {
/**
*
*/
public static String getElementText(Element element) {
StringBuffer buffer = new StringBuffer();
NodeList nodeList = element.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.TEXT_NODE || node.getNodeType() == Node.CDATA_SECTION_NODE) {
buffer.append(node.getNodeValue());
}
}
return buffer.toString();
}
}
Return the first element child with the specified qualified name.
/**
* 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.io.OutputStream;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Few simple utils to read DOM. This is originally from the Jakarta Commons
* Modeler.
*
* @author Costin Manolache
*/
public class Utils {
/**
* Return the first element child with the specified qualified name.
*
* @param parent
* @param ns
* @param lp
* @return
*/
public static Element getFirstChildWithName(Element parent, String ns, String lp) {
for (Node n = parent.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n instanceof Element) {
Element e = (Element)n;
String ens = (e.getNamespaceURI() == null) ? "" : e.getNamespaceURI();
if (ns.equals(ens) && lp.equals(e.getLocalName())) {
return e;
}
}
}
return null;
}
}
Return the first named Element found. Null if none.
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Utils {
/**
* Return a list of named Elements.
* @param element the containing Element
* @param name the tag name
* @return NodeList of matching elements
*/
public static NodeList getElementList(Element element, String name) {
return element.getElementsByTagName(name);
}
/**
* Return the first named Element found. Null if none.
* @param element the containing Element
* @param name the tag name
* @return matching Element (null if none)
*/
public static Element getElement(Element element, String name) {
NodeList nodeList = getElementList(element, name);
return (nodeList.getLength() == 0) ? null : (Element) nodeList.item(0);
}
}
Return the next sibling with a given name and type
import org.w3c.dom.Node;
public class Main {
/**
*/
public static Node getNext( Node current, String name, int type) {
Node first=current.getNextSibling();
if( first==null ) return null;
for (Node node = first; node != null;
node = node.getNextSibling()) {
if( type >= 0 && node.getNodeType() != type ) continue;
//System.out.println("getNode: " + name + " " + node.getNodeName());
if( name==null )
return node;
if( name.equals( node.getNodeName() ) ) {
return node;
}
}
return null;
}
}