xmlutil.java

来自「ejb3 java session bean」· Java 代码 · 共 925 行 · 第 1/3 页

JAVA
925 行
字号
  public static void removeAttributes(Element elem) {    if (elem.hasAttributes()) {      NamedNodeMap attributeMap = elem.getAttributes();      // since node maps are live, hold attributes in a separate collection      int n = attributeMap.getLength();      Attr[] attributes = new Attr[n];      for (int i = 0; i < n; i++)        attributes[i] = (Attr) attributeMap.item(i);      // now remove each attribute from the element      for (int i = 0; i < n; i++)        elem.removeAttributeNode(attributes[i]);    }  }  public static void removeChildNodes(Node node) {    for (Node current = node.getFirstChild(), next; current != null; current = next) {      next = current.getNextSibling();      node.removeChild(current);    }  }  public static Document createDocument() {    return getDocumentBuilder().newDocument();  }  /**   * Creates an element with the given qualified name. The returned element will be set as the   * document element of its owner document.   * @param name the qualified name of the element to create   * @return a new element with the specified <code>name</code>   */  public static Element createElement(QName name) {    String namespace = name.getNamespaceURI();    String localName = name.getLocalPart();    if (namespace.length() == 0)      return createElement(localName);    String prefix = name.getPrefix();    return createElement(namespace, prefix.length() > 0 ? prefix + ':' + localName : localName);  }  /**   * Creates an element with the given namespace URI and prefixed name. The returned element will be   * set as the document element of its owner document.   * @param namespaceURI the namespace URI of the element to create   * @param prefixedName the prefixed name of the element to instantiate   * @return a new element with the specified <code>namespaceURI</code> and   * <code>prefixedName</code>.   */  public static Element createElement(String namespaceURI, String prefixedName) {    Document doc = createDocument();    Element elem = doc.createElementNS(namespaceURI, prefixedName);    doc.appendChild(elem);    // some TrAX implementations do not fix up namespaces, declare namespace    String prefix = elem.getPrefix();    if (prefix != null)      addNamespaceDeclaration(elem, namespaceURI, prefix);    else      addNamespaceDeclaration(elem, namespaceURI);    return elem;  }  /**   * Creates an element with the given local name and neither namespace URI nor prefix. The returned   * element will be set as the document element of its owner document.   * @param localName the local name of the element to create   * @return a new element with the specified <code>localName</code>   */  public static Element createElement(String localName) {    Document doc = createDocument();    Element elem = doc.createElementNS(null, localName);    doc.appendChild(elem);    return elem;  }  /**   * Parses the XML document contained in the given string into a DOM document.   * @param text a string containing the document to parse   * @return a new DOM document representing the XML content   * @throws SAXException if any parse errors occur   */  public static Element parseText(String text) throws SAXException {    try {      return getDocumentBuilder().parse(new InputSource(new StringReader(text)))          .getDocumentElement();    }    catch (IOException e) {      // cannot happen, string reader doesn't throw I/O exceptions unless closed      throw new AssertionError(e);    }  }  public static Element parseResource(String resource) throws SAXException, IOException {    return parseResource(resource, ClassLoaderUtil.getClassLoader().getResource(resource));  }  public static DOMSource parseResource(String resource, Class cl) throws SAXException, IOException {    URL resourceURL = cl.getResource(resource);    Element elem = parseResource(resource, resourceURL);    return new DOMSource(elem, resourceURL.toExternalForm());  }  private static Element parseResource(String resource, URL location) throws SAXException,      IOException {    if (location == null)      throw new FileNotFoundException(resource);    InputStream inputStream = location.openStream();    try {      return getDocumentBuilder().parse(inputStream, resource).getDocumentElement();    }    finally {      inputStream.close();    }  }  /**   * Gets a validating document builder local to the current thread.   * @return a thread-local document builder   */  public static DocumentBuilder getDocumentBuilder() {    return (DocumentBuilder) documentBuilderLocal.get();  }  public static Map findNamespaceDeclarations(Element elem) {    Map namespaces = new HashMap();    findLocalNamespaceDeclarations(elem, namespaces);    // go up the parent hierarchy    for (Node parent = elem.getParentNode(); parent instanceof Element; parent = parent.getParentNode())      findLocalNamespaceDeclarations((Element) parent, namespaces);    return namespaces;  }  private static void findLocalNamespaceDeclarations(Element elem, Map namespaces) {    // traverse attributes to discover namespace declarations    NamedNodeMap attributes = elem.getAttributes();    for (int i = 0, n = attributes.getLength(); i < n; i++) {      Node attribute = attributes.item(i);      // is attribute a namespace declaration?      if (!BpelConstants.NS_XMLNS.equals(attribute.getNamespaceURI()))        continue;      // namespace declaration format:      // xmlns:prefix="namespaceURI" | xmlns="defaultNamespaceURI"      String prefix = attribute.getLocalName();      // exclude default and overriden namespace declarations      if ("xmlns".equals(prefix) || namespaces.containsKey(prefix))        continue;      String namespaceURI = attribute.getNodeValue();      namespaces.put(prefix, namespaceURI);    }  }  /**   * Retrieves the prefix associated with a namespace URI in the given context node.   * @param namespaceURI the namespace whose prefix is required   * @param contextNode the node where to search for namespace declarations   * @return the prefix associated with the namespace URI; the empty string indicates the default   * namespace, while <code>null</code> indicates no association   */  public static String getPrefix(String namespaceURI, Node contextNode) {    switch (contextNode.getNodeType()) {    case Node.ATTRIBUTE_NODE:      contextNode = ((Attr) contextNode).getOwnerElement();      break;    case Node.ELEMENT_NODE:      break;    default:      contextNode = contextNode.getParentNode();    }    while (contextNode != null && contextNode.getNodeType() == Node.ELEMENT_NODE) {      NamedNodeMap attributes = contextNode.getAttributes();      for (int i = 0, n = attributes.getLength(); i < n; i++) {        Node attr = attributes.item(i);        // is attribute a namespace declaration and matches the given URI?        if (BpelConstants.NS_XMLNS.equals(attr.getNamespaceURI())            && namespaceURI.equals(attr.getNodeValue())) {          String prefix = attr.getLocalName();          return "xmlns".equals(prefix) ? "" : prefix;        }      }      contextNode = contextNode.getParentNode();    }    return null;  }  public static String getNamespaceURI(String prefix, Node contextNode) {    return DOMUtils.getNamespaceURIFromPrefix(contextNode, prefix);  }  public static String generatePrefix(String base, Element contextElem) {    // check possible collision with namespace declarations    if (!contextElem.hasAttributeNS(BpelConstants.NS_XMLNS, base))      return base;    // collision detected, append a discriminator number    StringBuffer prefixBuffer = new StringBuffer(base);    for (int i = 1; i < Integer.MAX_VALUE; i++) {      String prefix = prefixBuffer.append(i).toString();      if (!contextElem.hasAttributeNS(BpelConstants.NS_XMLNS, prefix))        return prefix;      // remove appended number      prefixBuffer.setLength(base.length());    }    throw new Error("could not generate prefix from base: " + base);  }  public static TransformerFactory getTransformerFactory() {    return (TransformerFactory) transformerFactoryLocal.get();  }  public static Templates createTemplates(URL templateURL) throws TransformerException {    return getTransformerFactory().newTemplates(        new SAXSource(new InputSource(templateURL.toExternalForm())));  }  public static void writeFile(Node node, File file) throws IOException {    try {      // prepare identity transformer      Transformer xmlWriter = XmlUtil.getTransformerFactory().newTransformer();      // prepare output stream      OutputStream fileSink = new BufferedOutputStream(new FileOutputStream(file));      try {        xmlWriter.transform(new DOMSource(node), new StreamResult(fileSink));      }      finally {        fileSink.close();      }    }    catch (TransformerException e) {      Throwable cause = e.getCause();      if (cause instanceof IOException)        throw (IOException) cause;      // should not happen      throw new AssertionError(e);    }  }  private static class ElementPredicate implements Predicate {    static final Predicate INSTANCE = new ElementPredicate();    private ElementPredicate() {    }    public boolean evaluate(Object arg) {      return evaluate((Node) arg);    }    public static boolean evaluate(Node node) {      return node.getNodeType() == Node.ELEMENT_NODE;    }  }  private static class NamespaceElementPredicate implements Predicate {    private final String namespaceURI;    NamespaceElementPredicate(String namespaceURI) {      this.namespaceURI = namespaceURI;    }    public boolean evaluate(Object arg) {      return evaluate((Node) arg, namespaceURI);    }    public static boolean evaluate(Node node, String namespaceURI) {      return node.getNodeType() == Node.ELEMENT_NODE && nodeNamespaceURIEquals(node, namespaceURI);    }  }  private static class QualifiedNameElementPredicate implements Predicate {    private final String namespaceURI;    private final String localName;    QualifiedNameElementPredicate(String namespaceURI, String localName) {      this.namespaceURI = namespaceURI;      this.localName = localName;    }    public boolean evaluate(Object arg) {      return evaluate((Node) arg, namespaceURI, localName);    }    public static boolean evaluate(Node node, String namespaceURI, String localName) {      return node.getNodeType() == Node.ELEMENT_NODE          && nodeNameEquals(node, namespaceURI, localName);    }  }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?