Java/XML/DOM Attribute

Материал из Java эксперт
Версия от 07:11, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

An Attributes implementation that can perform more operations than the attribute list helper supplied with the standard SAX2 distribution.

 
/*
 * 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.xml.sax.Attributes;
/**
 * An Attributes implementation that can perform more operations than the
 * attribute list helper supplied with the standard SAX2 distribution.
 */
public class AttributesImpl implements Attributes {
  //
  // Data
  //
  /** Head node. */
  private ListNode head;
  /** Tail node. */
  private ListNode tail;
  /** Length. */
  private int length;
  //
  // Attributes methods
  //
  /** Returns the number of attributes. */
  public int getLength() {
    return length;
  }
  /** Returns the index of the specified attribute. */
  public int getIndex(String raw) {
    ListNode place = head;
    int index = 0;
    while (place != null) {
      if (place.raw.equals(raw)) {
        return index;
      }
      index++;
      place = place.next;
    }
    return -1;
  }
  /** Returns the index of the specified attribute. */
  public int getIndex(String uri, String local) {
    ListNode place = head;
    int index = 0;
    while (place != null) {
      if (place.uri.equals(uri) && place.local.equals(local)) {
        return index;
      }
      index++;
      place = place.next;
    }
    return -1;
  }
  /** Returns the attribute URI by index. */
  public String getURI(int index) {
    ListNode node = getListNodeAt(index);
    return node != null ? node.uri : null;
  } // getURI(int):String
  /** Returns the attribute local name by index. */
  public String getLocalName(int index) {
    ListNode node = getListNodeAt(index);
    return node != null ? node.local : null;
  } // getLocalName(int):String
  /** Returns the attribute raw name by index. */
  public String getQName(int index) {
    ListNode node = getListNodeAt(index);
    return node != null ? node.raw : null;
  } // getQName(int):String
  /** Returns the attribute type by index. */
  public String getType(int index) {
    ListNode node = getListNodeAt(index);
    return (node != null) ? node.type : null;
  } // getType(int):String
  /** Returns the attribute type by uri and local. */
  public String getType(String uri, String local) {
    ListNode node = getListNode(uri, local);
    return (node != null) ? node.type : null;
  } // getType(String,String):String
  /** Returns the attribute type by raw name. */
  public String getType(String raw) {
    ListNode node = getListNode(raw);
    return (node != null) ? node.type : null;
  } // getType(String):String
  /** Returns the attribute value by index. */
  public String getValue(int index) {
    ListNode node = getListNodeAt(index);
    return (node != null) ? node.value : null;
  } // getType(int):String
  /** Returns the attribute value by uri and local. */
  public String getValue(String uri, String local) {
    ListNode node = getListNode(uri, local);
    return (node != null) ? node.value : null;
  } // getType(String):String
  /** Returns the attribute value by raw name. */
  public String getValue(String raw) {
    ListNode node = getListNode(raw);
    return (node != null) ? node.value : null;
  } // getType(String):String
  //
  // Public methods
  //
  /** Adds an attribute. */
  public void addAttribute(String raw, String type, String value) {
    addAttribute(null, null, raw, type, value);
  }
  /** Adds an attribute. */
  public void addAttribute(String uri, String local, String raw, String type, String value) {
    ListNode node = new ListNode(uri, local, raw, type, value);
    if (length == 0) {
      head = node;
    } else {
      tail.next = node;
    }
    tail = node;
    length++;
  } // addAttribute(String,StringString,String,String)
  /** Inserts an attribute. */
  public void insertAttributeAt(int index, String raw, String type, String value) {
    insertAttributeAt(index, null, null, raw, type, value);
  }
  /** Inserts an attribute. */
  public void insertAttributeAt(int index, String uri, String local, String raw, String type,
      String value) {
    // if list is empty, add attribute
    if (length == 0 || index >= length) {
      addAttribute(uri, local, raw, type, value);
      return;
    }
    // insert at beginning of list
    ListNode node = new ListNode(uri, local, raw, type, value);
    if (index < 1) {
      node.next = head;
      head = node;
    } else {
      ListNode prev = getListNodeAt(index - 1);
      node.next = prev.next;
      prev.next = node;
    }
    length++;
  } // insertAttributeAt(int,String,String,String,String,String)
  /** Removes an attribute. */
  public void removeAttributeAt(int index) {
    if (length == 0) {
      return;
    }
    if (index == 0) {
      head = head.next;
      if (head == null) {
        tail = null;
      }
      length--;
    } else {
      ListNode prev = getListNodeAt(index - 1);
      ListNode node = getListNodeAt(index);
      if (node != null) {
        prev.next = node.next;
        if (node == tail) {
          tail = prev;
        }
        length--;
      }
    }
  } // removeAttributeAt(int)
  /** Removes the specified attribute. */
  public void removeAttribute(String raw) {
    removeAttributeAt(getIndex(raw));
  }
  /** Removes the specified attribute. */
  public void removeAttribute(String uri, String local) {
    removeAttributeAt(getIndex(uri, local));
  }
  //
  // Private methods
  //
  /** Returns the node at the specified index. */
  private ListNode getListNodeAt(int i) {
    for (ListNode place = head; place != null; place = place.next) {
      if (--i == -1) {
        return place;
      }
    }
    return null;
  } // getListNodeAt(int):ListNode
  /** Returns the first node with the specified uri and local. */
  public ListNode getListNode(String uri, String local) {
    if (uri != null && local != null) {
      ListNode place = head;
      while (place != null) {
        if (place.uri != null && place.local != null && place.uri.equals(uri)
            && place.local.equals(local)) {
          return place;
        }
        place = place.next;
      }
    }
    return null;
  } // getListNode(String,String):ListNode
  /** Returns the first node with the specified raw name. */
  private ListNode getListNode(String raw) {
    if (raw != null) {
      for (ListNode place = head; place != null; place = place.next) {
        if (place.raw != null && place.raw.equals(raw)) {
          return place;
        }
      }
    }
    return null;
  } // getListNode(String):ListNode
  //
  // Object methods
  //
  /** Returns a string representation of this object. */
  public String toString() {
    StringBuffer str = new StringBuffer();
    str.append("[");
    str.append("len=");
    str.append(length);
    str.append(", {");
    for (ListNode place = head; place != null; place = place.next) {
      str.append(place.toString());
      if (place.next != null) {
        str.append(", ");
      }
    }
    str.append("}]");
    return str.toString();
  } // toString():String
  //
  // Classes
  //
  /**
   * An attribute node.
   */
  static class ListNode {
    //
    // Data
    //
    /** Attribute uri. */
    public String uri;
    /** Attribute local. */
    public String local;
    /** Attribute raw. */
    public String raw;
    /** Attribute type. */
    public String type;
    /** Attribute value. */
    public String value;
    /** Next node. */
    public ListNode next;
    //
    // Constructors
    //
    /** Constructs a list node. */
    public ListNode(String uri, String local, String raw, String type, String value) {
      this.uri = uri;
      this.local = local;
      this.raw = raw;
      this.type = type;
      this.value = value;
    } // <init>(String,String,String,String,String)
    //
    // Object methods
    //
    /** Returns string representation of this object. */
    public String toString() {
      return raw != null ? raw : local;
    }
  } // class ListNode
} // class AttributesImpl





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());
      }
  }
}





Find Container With Attribute Value Or Create

  
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 findContainerWithAttributeValueElseCreate(
      Document document, Element parent, String element,
      String attributeName, String attributeValue) {
    NodeList nl = parent.getElementsByTagName(element);
    Element e;
    for (int i = 0; i < nl.getLength(); i++) {
      e = (Element) nl.item(i);
      if (e.getAttribute(attributeName).equals(attributeValue)) {
        return e;
      }
    }
    e = document.createElement(element);
    parent.appendChild(e);
    e.setAttribute(attributeName, attributeValue);
    return e;
  }
}





Find Container With Attribute Value Or Create And Set

  
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 findContainerWithAttributeValueElseCreateAndSet(
      Document document, Element parent, String element, String value,
      String attributeName, String attributeValue) {
    Element e = findContainerWithAttributeValueElseCreate(document, parent,
        element, attributeName, attributeValue);
    e.appendChild(document.createTextNode(value));
    return e;
  }
  public static Element findContainerWithAttributeValueElseCreate(
      Document document, Element parent, String element,
      String attributeName, String attributeValue) {
    NodeList nl = parent.getElementsByTagName(element);
    Element e;
    for (int i = 0; i < nl.getLength(); i++) {
      e = (Element) nl.item(i);
      if (e.getAttribute(attributeName).equals(attributeValue)) {
        return e;
      }
    }
    e = document.createElement(element);
    parent.appendChild(e);
    e.setAttribute(attributeName, attributeValue);
    return e;
  }
}





Find the first direct child with a given attribute.

  
import org.w3c.dom.Node;
/**
 *  
 *
 * @author Costin Manolache
 */
public class Main {
  /** Find the first direct child with a given attribute.
   * @param parent
   * @param elemName name of the element, or null for any 
   * @param attName attribute we"re looking for
   * @param attVal attribute value or null if we just want any
   */ 
  public static Node findChildWithAtt(Node parent, String elemName,
                                      String attName, String attVal) {
      
      Node child=DomUtil.getChild(parent, Node.ELEMENT_NODE);
      if( attVal== null ) {
          while( child!= null &&
                  ( elemName==null || elemName.equals( child.getNodeName())) && 
                  DomUtil.getAttribute(child, attName) != null ) {
              child=getNext(child, elemName, Node.ELEMENT_NODE );
          }
      } else {
          while( child!= null && 
                  ( elemName==null || elemName.equals( child.getNodeName())) && 
                  ! attVal.equals( DomUtil.getAttribute(child, attName)) ) {
              child=getNext(child, elemName, Node.ELEMENT_NODE );
          }
      }
      return child;        
  }  
  /** 
   */ 
  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;
  }
}





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();
  }
}





Get Attribute by 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;
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(Element element, QName attName) {
    return element.getAttributeNS(attName.getNamespaceURI(), attName.getLocalPart());
}
}





Get attribute"s value

   
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;

public class Main {
  // get attribute"s value
  public static String getValue(Attr attribute) {
      return attribute.getValue();
  } // getValue(Attr):String
 
}





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());
      }
  }
}





Recursive method to find a given attribute value

  
import javax.xml.namespace.QName;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Utils {
  /**
   * Recursive method to find a given attribute value
   */
  public static String recursiveGetAttributeValue(Element element, String attributeName) {
      String answer = null;
      try {
          answer = element.getAttribute(attributeName);
      } catch (Exception e) {
    
      }
      if (answer == null || answer.length() == 0) {
          Node parentNode = element.getParentNode();
          if (parentNode instanceof Element) {
              return recursiveGetAttributeValue((Element) parentNode, attributeName);
          }
      }
      return answer;
  }
}





Returns null, not "", for a nonexistent attribute

  
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
public class Utils {
  /**
   * Returns null, not "", for a nonexistent attribute.
   * 
   * @param e
   * @param attributeName
   * @return
   */
  public static String getAttributeValueEmptyNull(Element e, String attributeName) {
      Attr node = e.getAttributeNode(attributeName);
      if (node == null) {
          return null;
      }
      return node.getValue();
  }
}





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 getAttrValueNS(Element elem, String nsUri,
          String localName) {
      return elem.getAttributeNS(nsUri, localName);
  } // getAttrValueNS(Element, String):Attr
}





Retutns the value of the named attribute of the given element.

  
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
public class Utils {

  /**
   * <p>Retutns the value of the named attribute of the given
   * element. If there is no such attribute, returns null.</p>
   *
   * @param element element
   * @param name name
   * @return value
   */
  public static String getAttributeValue(Element element, String name)
  {
      Attr attribute = element.getAttributeNode(name);
      if(attribute == null) {
          return null;
      }
      else {
          return attribute.getValue();
      }
  }
}





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);
}
}