Java Tutorial/XML/DOM Attribute
Содержание
- 1 An encoder for converting text to be used within XML attribute values
- 2 Copy the attribues on one element to the other
- 3 Encode Xml Attribute
- 4 Find Element Or Create And Attribute
- 5 Find Element Or Create And Set Attribute
- 6 get all the attributes for an Element
- 7 Get an Attribute from an Element. Returns an empty String if none found
- 8 Get Attribute
- 9 Has Attribute
- 10 Output XML element Attributes
- 11 remove Attribute
- 12 Return a list of named Elements with a specific attribute value.
- 13 Returns the value of the attribute of the given element
- 14 return the right attribute node
- 15 return the value of the attribute of the given element with the given name
- 16 Set an Attribute in an Element
- 17 Set Attribute
An encoder for converting text to be used within XML attribute values
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.HashMap;
import java.util.Map;
/**
* An encoder useful for converting text to be used within XML attribute values.
* The following translations will be performed:
* <table cellspacing="0" cellpadding="1" border="1">
* <tr>
* <th>Raw (Unencoded)<br/>Character</th>
* <th>Translated (Encoded)<br/>Entity</th>
* </tr>
* <tr>
* <td> & </td>
* <td> &amp; </td>
* </tr>
* <tr>
* <td> < </td>
* <td> &lt; </td>
* </tr>
* <tr>
* <td> > </td>
* <td> &gt; </td>
* </tr>
* <tr>
* <td> " </td>
* <td> &quot; </td>
* </tr>
* <tr>
* <td> ' </td>
* <td> &#039; </td>
* </tr>
* <tr>
* <td>All Others</td>
* <td>No Translation</td>
* </tr>
* </table>
* </p>
*/
public class XmlValueEncoder {
private static final Map<String, Character> SPECIAL_ENTITIES;
static {
SPECIAL_ENTITIES = new HashMap<String, Character>();
SPECIAL_ENTITIES.put("quot", """);
SPECIAL_ENTITIES.put("gt", ">");
SPECIAL_ENTITIES.put("lt", "<");
SPECIAL_ENTITIES.put("amp", "&");
}
/**
* {@inheritDoc}
*
* @see org.jboss.dna.rumon.text.TextEncoder#encode(java.lang.String)
*/
public String encode( String text ) {
if (text == null) return null;
StringBuilder sb = new StringBuilder();
CharacterIterator iter = new StringCharacterIterator(text);
for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
switch (c) {
case "&":
sb.append("&");
break;
case """:
sb.append(""");
break;
case "<":
sb.append("<");
break;
case ">":
sb.append(">");
break;
case "\"":
sb.append("'");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
/**
* {@inheritDoc}
*
* @see org.jboss.dna.rumon.text.TextDecoder#decode(java.lang.String)
*/
public String decode( String encodedText ) {
if (encodedText == null) return null;
StringBuilder sb = new StringBuilder();
CharacterIterator iter = new StringCharacterIterator(encodedText);
for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
if (c == "&") {
int index = iter.getIndex();
do {
c = iter.next();
}
while (c != CharacterIterator.DONE && c != ";");
// We found a closing semicolon
if (c == ";") {
String s = encodedText.substring(index + 1, iter.getIndex());
if (SPECIAL_ENTITIES.containsKey(s)) {
sb.append(SPECIAL_ENTITIES.get(s));
continue;
}
if (s.length() > 0 && s.charAt(0) == "#") {
try {
sb.append((char) Short.parseShort(s.substring(1, s.length())));
continue;
}
catch (NumberFormatException nfe) {
// This is possible in malformed encodings, but let it fall through
}
}
}
// Malformed encoding, restore state and pass poorly encoded data back
c = "&";
iter.setIndex(index);
}
sb.append(c);
}
return sb.toString();
}
}
Copy the attribues on one element to the other
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
public class Utils {
public static void copyAttributes(Element from, Element to) {
NamedNodeMap attributes = from.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Attr node = (Attr) attributes.item(i);
to.setAttributeNS(node.getNamespaceURI(), node.getName(), node.getValue());
}
}
}
Encode Xml Attribute
/**
*
* The ObjectStyle Group Software License, version 1.1
* ObjectStyle Group - http://objectstyle.org/
*
* Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
* of the software. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if any,
* must include the following acknowlegement:
* "This product includes software developed by independent contributors
* and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
* or promote products derived from this software without prior written
* permission. For written permission, email
* "andrus at objectstyle dot org".
*
* 5. Products derived from this software may not be called "ObjectStyle"
* or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
* names without prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE OBJECTSTYLE GROUP OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many
* individuals and hosted on ObjectStyle Group web site. For more
* information on the ObjectStyle Group, please see
* <http://objectstyle.org/>.
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.ruparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* Contains various unorganized static utility methods used across Cayenne.
*
* @author Andrei Adamchik
*/
public class Util {
/**
* Encodes a string so that it can be used as an attribute value in an XML document.
* Will do conversion of the greater/less signs, quotes and ampersands.
*/
public static String encodeXmlAttribute(String str) {
if (str == null)
return null;
int len = str.length();
if (len == 0)
return str;
StringBuffer encoded = new StringBuffer();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if (c == "<")
encoded.append("<");
else if (c == "\"")
encoded.append(""");
else if (c == ">")
encoded.append(">");
else if (c == "\"")
encoded.append("'");
else if (c == "&")
encoded.append("&");
else
encoded.append(c);
}
return encoded.toString();
}
}
Find Element Or Create And Attribute
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 findElementElseCreateAndAttribute(Document document,
Element parent, String element, String attributeName,
String attributeValue) {
NodeList nl = parent.getElementsByTagName(element);
Element e = null;
if (nl.getLength() == 0) {
parent.appendChild(document.createElement(element));
e = (Element) parent.getElementsByTagName(element).item(0);
e.setAttribute(attributeName, attributeValue);
}
return e;
}
}
Find Element Or Create And Set Attribute
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 findElementElseCreateAndSetAndAttribute(
Document document, Element parent, String element, String value,
String attributeName, String attributeValue) {
Element e = findElementElseCreateAndAttribute(document, parent,
element, attributeName, attributeValue);
if (e != null)
e.appendChild(document.createTextNode(value));
return e;
}
public static Element findElementElseCreateAndAttribute(Document document,
Element parent, String element, String attributeName,
String attributeValue) {
NodeList nl = parent.getElementsByTagName(element);
Element e = null;
if (nl.getLength() == 0) {
parent.appendChild(document.createElement(element));
e = (Element) parent.getElementsByTagName(element).item(0);
e.setAttribute(attributeName, attributeValue);
}
return e;
}
}
get all the attributes for an Element
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
public class Main {
// get all the attributes for an Element
public static Attr[] getAttrs(Element elem) {
NamedNodeMap attrMap = elem.getAttributes();
Attr [] attrArray = new Attr[attrMap.getLength()];
for (int i=0; i<attrMap.getLength(); i++)
attrArray[i] = (Attr)attrMap.item(i);
return attrArray;
} // getAttrs(Element): Attr[]
}
Get an Attribute from an Element. Returns an empty String if none found
/**********************************************************************************
*
* 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 java.util.ArrayList;
import java.util.List;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Utils {
/**
* Get an Attribute from an Element. Returns an empty String if none found
* @param element the containing Element
* @param name the attribute name
* @return Attribute as a String
*/
public static String getAttribute(Element element, String name) {
return element.getAttribute(name);
}
/**
* Return a list of named Elements with a specific attribute value.
* @param element the containing Element
* @param name the tag name
* @param attribute Attribute name
* @param value Attribute value
* @param returnFirst Return only the first matching value?
* @return List of matching elements
*/
public static List selectElementsByAttributeValue(Element element, String name,
String attribute, String value,
boolean returnFirst) {
NodeList elementList = element.getElementsByTagName(name);
List resultList = new ArrayList();
for (int i = 0; i < elementList.getLength(); i++) {
if (getAttribute((Element) elementList.item(i), attribute).equals(value)) {
resultList.add(elementList.item(i));
if (returnFirst) {
break;
}
}
}
return resultList;
}
}
Get Attribute
/**
* 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.NamedNodeMap;
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 String getAttribute(Node element, String attName) {
NamedNodeMap attrs = element.getAttributes();
if (attrs == null) {
return null;
}
Node attN = attrs.getNamedItem(attName);
if (attN == null) {
return null;
}
return attN.getNodeValue();
}
}
Has Attribute
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
public class Utils {
public static boolean hasAttribute(Element element, String value) {
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Node node = attributes.item(i);
if (value.equals(node.getNodeValue())) {
return true;
}
}
return false;
}
}
Output XML element Attributes
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
public class Utils {
public static void printAttributes(Element element) {
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Node node = attributes.item(i);
System.err.println("## prefix=" + node.getPrefix() + " localname:" + node.getLocalName()
+ " value=" + node.getNodeValue());
}
}
}
remove Attribute
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
/**
*
*
* @author Costin Manolache
*/
public class Main {
public static void removeAttribute( Node node, String attName ) {
NamedNodeMap attributes=node.getAttributes();
attributes.removeNamedItem(attName);
}
}
Return a list of named Elements with a specific attribute value.
/**********************************************************************************
*
* 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 java.util.ArrayList;
import java.util.List;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Utils {
/**
* Get an Attribute from an Element. Returns an empty String if none found
* @param element the containing Element
* @param name the attribute name
* @return Attribute as a String
*/
public static String getAttribute(Element element, String name) {
return element.getAttribute(name);
}
/**
* Return a list of named Elements with a specific attribute value.
* @param element the containing Element
* @param name the tag name
* @param attribute Attribute name
* @param value Attribute value
* @param returnFirst Return only the first matching value?
* @return List of matching elements
*/
public static List selectElementsByAttributeValue(Element element, String name,
String attribute, String value,
boolean returnFirst) {
NodeList elementList = element.getElementsByTagName(name);
List resultList = new ArrayList();
for (int i = 0; i < elementList.getLength(); i++) {
if (getAttribute((Element) elementList.item(i), attribute).equals(value)) {
resultList.add(elementList.item(i));
if (returnFirst) {
break;
}
}
}
return resultList;
}
}
Returns the value of the attribute of the given element
/**
* 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 {
/**
* Utility class, no constructor.
*/
private XMLUtils() {
}
/**
* Returns the value of the attribute of the given element.
* @param base the element from where to search.
* @param name of the attribute to get.
* @return the value of this element.
*/
public static String getAttributeValue(final Element base, final String name) {
// get attribute of this element...
NamedNodeMap mapAttributes = base.getAttributes();
Node node = mapAttributes.getNamedItem(name);
if (node != null) {
return node.getNodeValue();
}
return null;
}
}
return the right attribute node
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
public class Main {
// return the right attribute node
public static Attr getAttr(Element elem, String name) {
return elem.getAttributeNode(name);
} // getAttr(Element, String):Attr
}
return the value of the attribute of the given element with the given name
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
public class Main {
// return the value of the attribute of the given element with the given name
public static String getAttrValue(Element elem, String name) {
return elem.getAttribute(name);
} // getAttr(Element, String):Attr
}
Set an Attribute in an Element
import org.w3c.dom.Element;
public class Utils {
/**
* Set an Attribute in an Element
* @param element the containing Element
* @param name the attribute name
* @param value the attribute value
*/
public static void setAttribute(Element element, String name, String value) {
element.setAttribute(name, value);
}
}
Set Attribute
/**
* 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.NamedNodeMap;
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 void setAttribute(Node node, String attName, String val) {
NamedNodeMap attributes = node.getAttributes();
Node attNode = node.getOwnerDocument().createAttribute(attName);
attNode.setNodeValue(val);
attributes.setNamedItem(attNode);
}
}