Java Code Examples for org.w3c.dom.Document#getImplementation()

The following examples show how to use org.w3c.dom.Document#getImplementation() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public static String elementToString(Element element) {
	try {
		if (element == null) {
                               /* return an empty string because, the other way around works the same,
                               where if we give a empty string as the XML, we get a null element
                               from "stringToElement" */
			return "";
		}
           Document document = element.getOwnerDocument();
           DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
           LSSerializer serializer = domImplLS.createLSSerializer();
           //by default its true, so set it to false to get String without xml-declaration
           serializer.getDomConfig().setParameter(XML_DECLARATION, false);
           return serializer.writeToString(element);
	} catch (Exception e) {
		log.error("Error while convering element to string: " + e.getMessage(), e);
		return null;
	}
}
 
Example 2
public void load(File f) throws ConfigPersisterException {
    try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(f);

		DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
	    LSSerializer lsSerializer = domImplementation.createLSSerializer();
	    String configString = lsSerializer.writeToString(doc);

    	_config = (Config) _xstream.fromXML(convertToCurrent(configString));
    	setConfigPath(f);
	} catch (Exception e) {
		throw new ConfigPersisterException(e);
	}
}
 
Example 3
Source Project: openhab1-addons   File: Helper.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/***
 * Helper method which converts XML Document into pretty formatted string
 *
 * @param doc to convert
 * @return converted XML as String
 */
public static String documentToString(Document doc) {

    String strMsg = "";
    try {
        DOMImplementation domImpl = doc.getImplementation();
        DOMImplementationLS domImplLS = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");
        LSSerializer lsSerializer = domImplLS.createLSSerializer();
        lsSerializer.getDomConfig().setParameter("format-pretty-print", true);

        Writer stringWriter = new StringWriter();
        LSOutput lsOutput = domImplLS.createLSOutput();
        lsOutput.setEncoding("UTF-8");
        lsOutput.setCharacterStream(stringWriter);
        lsSerializer.write(doc, lsOutput);
        strMsg = stringWriter.toString();
    } catch (Exception e) {
        logger.warn("Error occurred when converting document to string", e);
    }
    return strMsg;
}
 
Example 4
/**
 * Saves the process configuration.
 */
private void saveConfiguration(Document docXMLConfig) {
  String fileToSaveConf = properties.getSaveRemoteConfig();
  if (fileToSaveConf.length() > 0 && docXMLConfig != null) {
    log.info("saveConfiguration - saving the process configuration XML in a file " + fileToSaveConf + " due to user request");

    File file = new File(fileToSaveConf);
    if (file.isDirectory() || !fileToSaveConf.endsWith(".xml")) {
      throw new RuntimeException("Path to which to save remote config must end with '.xml'");
    }

    try {
      DOMImplementationLS domImplementation = (DOMImplementationLS) docXMLConfig.getImplementation();
      LSSerializer lsSerializer = domImplementation.createLSSerializer();
      lsSerializer.writeToURI(docXMLConfig, file.toURI().toURL().toString());
    } catch (java.io.IOException ex) {
      log.error("saveConfiguration - Could not save the configuration to the file " + fileToSaveConf, ex);
    }
  }
}
 
Example 5
Source Project: Doradus   File: XmlUtils.java    License: Apache License 2.0 6 votes vote down vote up
static public String getInnerXmlText(Node xmlNode)
{
    StringBuilder result = new StringBuilder();

    Document xmlDocument = xmlNode.getOwnerDocument();
    DOMImplementation xmlDocumentImpl = xmlDocument.getImplementation();
    DOMImplementationLS lsImpl = (DOMImplementationLS) xmlDocumentImpl.getFeature("LS", "3.0");
    LSSerializer lsSerializer = lsImpl.createLSSerializer();

    NodeList childNodes = xmlNode.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        String childText = lsSerializer.writeToString(childNodes.item(i));
        int pos = childText.indexOf("?>");
        if (pos > -1) {
            childText = childText.substring(pos + 2);
        }
        result.append(childText);
    }

    return result.toString();
}
 
Example 6
public void load(File f) throws ConfigPersisterException {
    try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(f);

		DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
	    LSSerializer lsSerializer = domImplementation.createLSSerializer();
	    String configString = lsSerializer.writeToString(doc);

    	_config = (Config) _xstream.fromXML(convertToCurrent(configString));
    	setConfigPath(f);
	} catch (Exception e) {
		throw new ConfigPersisterException(e);
	}
}
 
Example 7
Source Project: syndesis   File: LocalResolver.java    License: Apache License 2.0 5 votes vote down vote up
public LocalResolver() {
    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (final ParserConfigurationException e) {
        throw new IllegalStateException(e);
    }
    final Document document = documentBuilder.newDocument();

    lsImplementation = (DOMImplementationLS) document.getImplementation();
}
 
Example 8
public String buildXMLString(int symStd)
{
    Document xml = buildXML(symStd);
    DOMImplementationLS domImplLS = (DOMImplementationLS)xml.getImplementation();
    LSSerializer serializer = domImplLS.createLSSerializer();
    String strXML = serializer.writeToString(xml);
    return strXML;
}
 
Example 9
Source Project: juddi   File: MappingApiToModel.java    License: Apache License 2.0 5 votes vote down vote up
private static String serializeTransformElement(Element xformEl) throws DOMException, LSException {
                Document document = xformEl.getOwnerDocument();
                DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
                LSSerializer serializer = domImplLS.createLSSerializer();
//        serializer.getDomConfig().setParameter("namespaces", true);
//        serializer.getDomConfig().setParameter("namespace-declarations", true);
                serializer.getDomConfig().setParameter("canonical-form", false);
                serializer.getDomConfig().setParameter("xml-declaration", false);
                String str = serializer.writeToString(xformEl);
                return str;
        }
 
Example 10
/**
 * Serialize XML Node to string
 * <p>
 * Note: this method is supposed to be faster than the Transform version but the output control
 * is limited. If node is Document node, it will output XML PI which sometimes we want to avoid.
 * 
 * @param doc XML document
 * @param node Node to be serialized
 * @param encoding encoding for the output
 * @return String representation of the Document
 * @throws IOException
 */
public static String serializeToStringLS(Document doc, Node node, String encoding) throws IOException {
	DOMImplementationLS domImpl = (DOMImplementationLS) doc.getImplementation();
       LSSerializer lsSerializer = domImpl.createLSSerializer();
       LSOutput output = domImpl.createLSOutput();
       output.setEncoding(encoding);
       StringWriter writer = new StringWriter();
       output.setCharacterStream(writer);
       lsSerializer.write(node, output);
       writer.flush();
       
       return writer.toString();
}
 
Example 11
Source Project: saml-sdk-java   File: SAMLClient.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private String createAuthnRequest(String requestId)
    throws SAMLException
{
    XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

    SAMLObjectBuilder<AuthnRequest> builder =
        (SAMLObjectBuilder<AuthnRequest>) builderFactory
        .getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME);

    SAMLObjectBuilder<Issuer> issuerBuilder =
        (SAMLObjectBuilder<Issuer>) builderFactory
        .getBuilder(Issuer.DEFAULT_ELEMENT_NAME);

    AuthnRequest request = builder.buildObject();
    request.setAssertionConsumerServiceURL(spConfig.getAcs().toString());
    request.setDestination(idpConfig.getLoginUrl().toString());
    request.setIssueInstant(new DateTime());
    request.setID(requestId);

    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(spConfig.getEntityId());
    request.setIssuer(issuer);

    try {
        // samlobject to xml dom object
        Element elem = Configuration.getMarshallerFactory()
            .getMarshaller(request)
            .marshall(request);

        // and to a string...
        Document document = elem.getOwnerDocument();
        DOMImplementationLS domImplLS = (DOMImplementationLS) document
            .getImplementation();
        LSSerializer serializer = domImplLS.createLSSerializer();
        serializer.getDomConfig().setParameter("xml-declaration", false);
        return serializer.writeToString(elem);
    }
    catch (MarshallingException e) {
        throw new SAMLException(e);
    }
}
 
Example 12
/**
 * Obtain the XPath-model parent of a DOM node -- ownerElement for Attrs,
 * parent for other nodes.
 * <p>
 * Background: The DOM believes that you must be your Parent's
 * Child, and thus Attrs don't have parents. XPath said that Attrs
 * do have their owning Element as their parent. This function
 * bridges the difference, either by using the DOM Level 2 ownerElement
 * function or by using a "silly and expensive function" in Level 1
 * DOMs.
 * <p>
 * (There's some discussion of future DOMs generalizing ownerElement
 * into ownerNode and making it work on all types of nodes. This
 * still wouldn't help the users of Level 1 or Level 2 DOMs)
 * <p>
 *
 * @param node Node whose XPath parent we want to obtain
 *
 * @return the parent of the node, or the ownerElement if it's an
 * Attr node, or null if the node is an orphan.
 *
 * @throws RuntimeException if the Document has no root element.
 * This can't arise if the Document was created
 * via the DOM Level 2 factory methods, but is possible if other
 * mechanisms were used to obtain it
 */
public static Node getParentOfNode(Node node) throws RuntimeException
{
  Node parent;
  short nodeType = node.getNodeType();

  if (Node.ATTRIBUTE_NODE == nodeType)
  {
    Document doc = node.getOwnerDocument();
        /*
    TBD:
    if(null == doc)
    {
      throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT, null));//"Attribute child does not have an owner document!");
    }
    */

        // Given how expensive the tree walk may be, we should first ask
        // whether this DOM can answer the question for us. The additional
        // test does slow down Level 1 DOMs slightly. DOMHelper2, which
        // is currently specialized for Xerces, assumes it can use the
        // Level 2 solution. We might want to have an intermediate stage,
        // which would assume DOM Level 2 but not assume Xerces.
        //
        // (Shouldn't have to check whether impl is null in a compliant DOM,
        // but let's be paranoid for a moment...)
        DOMImplementation impl=doc.getImplementation();
        if(impl!=null && impl.hasFeature("Core","2.0"))
        {
                parent=((Attr)node).getOwnerElement();
                return parent;
        }

        // DOM Level 1 solution, as fallback. Hugely expensive.

    Element rootElem = doc.getDocumentElement();

    if (null == rootElem)
    {
      throw new RuntimeException(
        XMLMessages.createXMLMessage(
          XMLErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT_ELEMENT,
          null));  //"Attribute child does not have an owner document element!");
    }

    parent = locateAttrParent(rootElem, node);

      }
  else
  {
    parent = node.getParentNode();

    // if((Node.DOCUMENT_NODE != nodeType) && (null == parent))
    // {
    //   throw new RuntimeException("Child does not have parent!");
    // }
  }

  return parent;
}
 
Example 13
private CombinedQueryDefinitionImpl parseCombinedQuery(RawCombinedQueryDefinition qdef) {
  DOMHandle handle = new DOMHandle();
  HandleAccessor.receiveContent(handle, HandleAccessor.contentAsString(qdef.getHandle()));
  Document combinedQueryXml = handle.get();
  DOMImplementationLS domImplementation = (DOMImplementationLS) combinedQueryXml.getImplementation();
  LSSerializer lsSerializer = domImplementation.createLSSerializer();
  lsSerializer.getDomConfig().setParameter("xml-declaration", false);

  NodeList nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "options");
  Node n = nl.item(0);
  String options = null;
  StringHandle optionsHandle = null;
  if (n != null) {
    options = lsSerializer.writeToString(n);
    optionsHandle = new StringHandle(options).withFormat(Format.XML);
  }

  //TODO this could be more than one string...
  nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "qtext");
  n = nl.item(0);
  String qtext = null;
  if (n != null) {
    qtext = lsSerializer.writeToString(n);
  }

  nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "sparql");
  n = nl.item(0);
  String sparql = null;
  if (n != null) {
    sparql = lsSerializer.writeToString(n);
  }

  nl = combinedQueryXml.getElementsByTagNameNS("http://marklogic.com/appservices/search", "query");
  n = nl.item(0);
  String query = null;
  if (n != null) {
    query = lsSerializer.writeToString(nl.item(0));
  }
  StringHandle structuredQueryHandle = new StringHandle().with(query).withFormat(Format.XML);
  RawStructuredQueryDefinition structuredQueryDefinition =
    new RawQueryDefinitionImpl.Structured(structuredQueryHandle);
  return new CombinedQueryDefinitionImpl(structuredQueryDefinition,
    optionsHandle, qtext, sparql);
}
 
Example 14
private void getNotifications(Integer userId, HttpServletRequest request, HttpServletResponse response)
    throws IOException {
Document doc = NotificationServlet.docBuilder.newDocument();
Element notificationsElement = doc.createElement("Notifications");
doc.appendChild(notificationsElement);

Long lessonId = WebUtil.readLongParam(request, CentralConstants.PARAM_LESSON_ID, true);
Integer limit = WebUtil.readIntParam(request, "limit", true);
Integer offset = WebUtil.readIntParam(request, "offset", true);
Boolean pendingOnly = WebUtil.readBooleanParam(request, "pendingOnly", true);

List<Subscription> subscriptions = eventNotificationService
	.getNotificationSubscriptions(lessonId, userId, pendingOnly, limit, offset);
for (Subscription subscription : subscriptions) {
    Element notificationElement = doc.createElement("Notification");

    notificationElement.setAttribute("id", subscription.getUid().toString());

    Boolean pending = !DeliveryMethodNotification.LAST_OPERATION_SEEN
	    .equals(subscription.getLastOperationMessage());
    notificationElement.setAttribute("pending", pending.toString());

    Long notificationLessonId = subscription.getEvent().getEventSessionId();
    if (notificationLessonId != null) {
	notificationElement.setAttribute("lessonId", notificationLessonId.toString());
    }

    String message = subscription.getEvent().getMessage();
    Matcher matcher = NotificationServlet.anchorPattern.matcher(message);
    if (matcher.find()) {
	String href = StringEscapeUtils.escapeXml(matcher.group(2));
	notificationElement.setAttribute("href", href);
	message = matcher.group(3);
    }
    notificationElement.appendChild(doc.createCDATASection(message));

    notificationsElement.appendChild(notificationElement);
}

response.setContentType("text/xml");
response.setCharacterEncoding("UTF-8");

DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
LSOutput lsOutput = domImplementation.createLSOutput();
lsOutput.setEncoding("UTF-8");
lsOutput.setByteStream(response.getOutputStream());
lsSerializer.write(doc, lsOutput);
   }
 
Example 15
/**
 * Obtain the XPath-model parent of a DOM node -- ownerElement for Attrs,
 * parent for other nodes.
 * <p>
 * Background: The DOM believes that you must be your Parent's
 * Child, and thus Attrs don't have parents. XPath said that Attrs
 * do have their owning Element as their parent. This function
 * bridges the difference, either by using the DOM Level 2 ownerElement
 * function or by using a "silly and expensive function" in Level 1
 * DOMs.
 * <p>
 * (There's some discussion of future DOMs generalizing ownerElement
 * into ownerNode and making it work on all types of nodes. This
 * still wouldn't help the users of Level 1 or Level 2 DOMs)
 * <p>
 *
 * @param node Node whose XPath parent we want to obtain
 *
 * @return the parent of the node, or the ownerElement if it's an
 * Attr node, or null if the node is an orphan.
 *
 * @throws RuntimeException if the Document has no root element.
 * This can't arise if the Document was created
 * via the DOM Level 2 factory methods, but is possible if other
 * mechanisms were used to obtain it
 */
public static Node getParentOfNode(Node node) throws RuntimeException
{
  Node parent;
  short nodeType = node.getNodeType();

  if (Node.ATTRIBUTE_NODE == nodeType)
  {
    Document doc = node.getOwnerDocument();
        /*
    TBD:
    if(null == doc)
    {
      throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT, null));//"Attribute child does not have an owner document!");
    }
    */

        // Given how expensive the tree walk may be, we should first ask
        // whether this DOM can answer the question for us. The additional
        // test does slow down Level 1 DOMs slightly. DOMHelper2, which
        // is currently specialized for Xerces, assumes it can use the
        // Level 2 solution. We might want to have an intermediate stage,
        // which would assume DOM Level 2 but not assume Xerces.
        //
        // (Shouldn't have to check whether impl is null in a compliant DOM,
        // but let's be paranoid for a moment...)
        DOMImplementation impl=doc.getImplementation();
        if(impl!=null && impl.hasFeature("Core","2.0"))
        {
                parent=((Attr)node).getOwnerElement();
                return parent;
        }

        // DOM Level 1 solution, as fallback. Hugely expensive.

    Element rootElem = doc.getDocumentElement();

    if (null == rootElem)
    {
      throw new RuntimeException(
        XMLMessages.createXMLMessage(
          XMLErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT_ELEMENT,
          null));  //"Attribute child does not have an owner document element!");
    }

    parent = locateAttrParent(rootElem, node);

      }
  else
  {
    parent = node.getParentNode();

    // if((Node.DOCUMENT_NODE != nodeType) && (null == parent))
    // {
    //   throw new RuntimeException("Child does not have parent!");
    // }
  }

  return parent;
}
 
Example 16
@Test
public void testDOMErrorHandler() {

    final String XML_DOCUMENT = "<?xml version=\"1.0\"?>" + "<hello>" + "world" + "</hello>";

    StringReader stringReader = new StringReader(XML_DOCUMENT);
    InputSource inputSource = new InputSource(stringReader);
    Document doc = null;
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        // LSSerializer defaults to Namespace processing
        // so parsing must also
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder parser = documentBuilderFactory.newDocumentBuilder();
        doc = parser.parse(inputSource);

    } catch (Throwable e) {
        e.printStackTrace();
        Assert.fail(e.toString());
    }

    DOMImplementation impl = doc.getImplementation();
    DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer writer = implLS.createLSSerializer();

    System.out.println("Serializer is: " + implLS.getClass().getName() + " " + implLS);

    DOMErrorHandlerImpl eh = new DOMErrorHandlerImpl();
    writer.getDomConfig().setParameter("error-handler", eh);

    boolean serialized = false;
    try {
        serialized = writer.write(doc, new Output());

        // unexpected success
        Assert.fail("Serialized without raising an LSException due to " + "'no-output-specified'.");
    } catch (LSException lsException) {
        // expected exception
        System.out.println("Expected LSException: " + lsException.toString());
        // continue processing
    }

    Assert.assertFalse(serialized, "Expected writer.write(doc, new Output()) == false");

    Assert.assertTrue(eh.NoOutputSpecifiedErrorReceived, "'no-output-specified' error was expected");
}
 
Example 17
Source Project: hottub   File: DOMHelper.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Obtain the XPath-model parent of a DOM node -- ownerElement for Attrs,
 * parent for other nodes.
 * <p>
 * Background: The DOM believes that you must be your Parent's
 * Child, and thus Attrs don't have parents. XPath said that Attrs
 * do have their owning Element as their parent. This function
 * bridges the difference, either by using the DOM Level 2 ownerElement
 * function or by using a "silly and expensive function" in Level 1
 * DOMs.
 * <p>
 * (There's some discussion of future DOMs generalizing ownerElement
 * into ownerNode and making it work on all types of nodes. This
 * still wouldn't help the users of Level 1 or Level 2 DOMs)
 * <p>
 *
 * @param node Node whose XPath parent we want to obtain
 *
 * @return the parent of the node, or the ownerElement if it's an
 * Attr node, or null if the node is an orphan.
 *
 * @throws RuntimeException if the Document has no root element.
 * This can't arise if the Document was created
 * via the DOM Level 2 factory methods, but is possible if other
 * mechanisms were used to obtain it
 */
public static Node getParentOfNode(Node node) throws RuntimeException
{
  Node parent;
  short nodeType = node.getNodeType();

  if (Node.ATTRIBUTE_NODE == nodeType)
  {
    Document doc = node.getOwnerDocument();
        /*
    TBD:
    if(null == doc)
    {
      throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT, null));//"Attribute child does not have an owner document!");
    }
    */

        // Given how expensive the tree walk may be, we should first ask
        // whether this DOM can answer the question for us. The additional
        // test does slow down Level 1 DOMs slightly. DOMHelper2, which
        // is currently specialized for Xerces, assumes it can use the
        // Level 2 solution. We might want to have an intermediate stage,
        // which would assume DOM Level 2 but not assume Xerces.
        //
        // (Shouldn't have to check whether impl is null in a compliant DOM,
        // but let's be paranoid for a moment...)
        DOMImplementation impl=doc.getImplementation();
        if(impl!=null && impl.hasFeature("Core","2.0"))
        {
                parent=((Attr)node).getOwnerElement();
                return parent;
        }

        // DOM Level 1 solution, as fallback. Hugely expensive.

    Element rootElem = doc.getDocumentElement();

    if (null == rootElem)
    {
      throw new RuntimeException(
        XMLMessages.createXMLMessage(
          XMLErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT_ELEMENT,
          null));  //"Attribute child does not have an owner document element!");
    }

    parent = locateAttrParent(rootElem, node);

      }
  else
  {
    parent = node.getParentNode();

    // if((Node.DOCUMENT_NODE != nodeType) && (null == parent))
    // {
    //   throw new RuntimeException("Child does not have parent!");
    // }
  }

  return parent;
}
 
Example 18
/**
 * Obtain the XPath-model parent of a DOM node -- ownerElement for Attrs,
 * parent for other nodes.
 * <p>
 * Background: The DOM believes that you must be your Parent's
 * Child, and thus Attrs don't have parents. XPath said that Attrs
 * do have their owning Element as their parent. This function
 * bridges the difference, either by using the DOM Level 2 ownerElement
 * function or by using a "silly and expensive function" in Level 1
 * DOMs.
 * <p>
 * (There's some discussion of future DOMs generalizing ownerElement
 * into ownerNode and making it work on all types of nodes. This
 * still wouldn't help the users of Level 1 or Level 2 DOMs)
 * <p>
 *
 * @param node Node whose XPath parent we want to obtain
 *
 * @return the parent of the node, or the ownerElement if it's an
 * Attr node, or null if the node is an orphan.
 *
 * @throws RuntimeException if the Document has no root element.
 * This can't arise if the Document was created
 * via the DOM Level 2 factory methods, but is possible if other
 * mechanisms were used to obtain it
 */
public static Node getParentOfNode(Node node) throws RuntimeException
{
  Node parent;
  short nodeType = node.getNodeType();

  if (Node.ATTRIBUTE_NODE == nodeType)
  {
    Document doc = node.getOwnerDocument();
        /*
    TBD:
    if(null == doc)
    {
      throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT, null));//"Attribute child does not have an owner document!");
    }
    */

        // Given how expensive the tree walk may be, we should first ask
        // whether this DOM can answer the question for us. The additional
        // test does slow down Level 1 DOMs slightly. DOMHelper2, which
        // is currently specialized for Xerces, assumes it can use the
        // Level 2 solution. We might want to have an intermediate stage,
        // which would assume DOM Level 2 but not assume Xerces.
        //
        // (Shouldn't have to check whether impl is null in a compliant DOM,
        // but let's be paranoid for a moment...)
        DOMImplementation impl=doc.getImplementation();
        if(impl!=null && impl.hasFeature("Core","2.0"))
        {
                parent=((Attr)node).getOwnerElement();
                return parent;
        }

        // DOM Level 1 solution, as fallback. Hugely expensive.

    Element rootElem = doc.getDocumentElement();

    if (null == rootElem)
    {
      throw new RuntimeException(
        XMLMessages.createXMLMessage(
          XMLErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT_ELEMENT,
          null));  //"Attribute child does not have an owner document element!");
    }

    parent = locateAttrParent(rootElem, node);

      }
  else
  {
    parent = node.getParentNode();

    // if((Node.DOCUMENT_NODE != nodeType) && (null == parent))
    // {
    //   throw new RuntimeException("Child does not have parent!");
    // }
  }

  return parent;
}
 
Example 19
/**
 * Obtain the XPath-model parent of a DOM node -- ownerElement for Attrs,
 * parent for other nodes.
 * <p>
 * Background: The DOM believes that you must be your Parent's
 * Child, and thus Attrs don't have parents. XPath said that Attrs
 * do have their owning Element as their parent. This function
 * bridges the difference, either by using the DOM Level 2 ownerElement
 * function or by using a "silly and expensive function" in Level 1
 * DOMs.
 * <p>
 * (There's some discussion of future DOMs generalizing ownerElement
 * into ownerNode and making it work on all types of nodes. This
 * still wouldn't help the users of Level 1 or Level 2 DOMs)
 * <p>
 *
 * @param node Node whose XPath parent we want to obtain
 *
 * @return the parent of the node, or the ownerElement if it's an
 * Attr node, or null if the node is an orphan.
 *
 * @throws RuntimeException if the Document has no root element.
 * This can't arise if the Document was created
 * via the DOM Level 2 factory methods, but is possible if other
 * mechanisms were used to obtain it
 */
public static Node getParentOfNode(Node node) throws RuntimeException
{
  Node parent;
  short nodeType = node.getNodeType();

  if (Node.ATTRIBUTE_NODE == nodeType)
  {
    Document doc = node.getOwnerDocument();
        /*
    TBD:
    if(null == doc)
    {
      throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT, null));//"Attribute child does not have an owner document!");
    }
    */

        // Given how expensive the tree walk may be, we should first ask
        // whether this DOM can answer the question for us. The additional
        // test does slow down Level 1 DOMs slightly. DOMHelper2, which
        // is currently specialized for Xerces, assumes it can use the
        // Level 2 solution. We might want to have an intermediate stage,
        // which would assume DOM Level 2 but not assume Xerces.
        //
        // (Shouldn't have to check whether impl is null in a compliant DOM,
        // but let's be paranoid for a moment...)
        DOMImplementation impl=doc.getImplementation();
        if(impl!=null && impl.hasFeature("Core","2.0"))
        {
                parent=((Attr)node).getOwnerElement();
                return parent;
        }

        // DOM Level 1 solution, as fallback. Hugely expensive.

    Element rootElem = doc.getDocumentElement();

    if (null == rootElem)
    {
      throw new RuntimeException(
        XMLMessages.createXMLMessage(
          XMLErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT_ELEMENT,
          null));  //"Attribute child does not have an owner document element!");
    }

    parent = locateAttrParent(rootElem, node);

      }
  else
  {
    parent = node.getParentNode();

    // if((Node.DOCUMENT_NODE != nodeType) && (null == parent))
    // {
    //   throw new RuntimeException("Child does not have parent!");
    // }
  }

  return parent;
}
 
Example 20
Source Project: j2objc   File: DOMHelper.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Obtain the XPath-model parent of a DOM node -- ownerElement for Attrs,
 * parent for other nodes. 
 * <p>
 * Background: The DOM believes that you must be your Parent's
 * Child, and thus Attrs don't have parents. XPath said that Attrs
 * do have their owning Element as their parent. This function
 * bridges the difference, either by using the DOM Level 2 ownerElement
 * function or by using a "silly and expensive function" in Level 1
 * DOMs.
 * <p>
 * (There's some discussion of future DOMs generalizing ownerElement 
 * into ownerNode and making it work on all types of nodes. This
 * still wouldn't help the users of Level 1 or Level 2 DOMs)
 * <p>
 *
 * @param node Node whose XPath parent we want to obtain
 *
 * @return the parent of the node, or the ownerElement if it's an
 * Attr node, or null if the node is an orphan.
 *
 * @throws RuntimeException if the Document has no root element.
 * This can't arise if the Document was created
 * via the DOM Level 2 factory methods, but is possible if other
 * mechanisms were used to obtain it
 */
public static Node getParentOfNode(Node node) throws RuntimeException
{
  Node parent;
  short nodeType = node.getNodeType();

  if (Node.ATTRIBUTE_NODE == nodeType)
  {
    Document doc = node.getOwnerDocument();
        /*
    TBD:
    if(null == doc)
    {
      throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT, null));//"Attribute child does not have an owner document!");
    }
    */

        // Given how expensive the tree walk may be, we should first ask 
        // whether this DOM can answer the question for us. The additional
        // test does slow down Level 1 DOMs slightly. DOMHelper2, which
        // is currently specialized for Xerces, assumes it can use the
        // Level 2 solution. We might want to have an intermediate stage,
        // which would assume DOM Level 2 but not assume Xerces.
        //
        // (Shouldn't have to check whether impl is null in a compliant DOM,
        // but let's be paranoid for a moment...)
        DOMImplementation impl=doc.getImplementation();
        if(impl!=null && impl.hasFeature("Core","2.0"))
        {
                parent=((Attr)node).getOwnerElement();
                return parent;
        }

        // DOM Level 1 solution, as fallback. Hugely expensive. 

    Element rootElem = doc.getDocumentElement();

    if (null == rootElem)
    {
      throw new RuntimeException(
        XMLMessages.createXMLMessage(
          XMLErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT_ELEMENT,
          null));  //"Attribute child does not have an owner document element!");
    }

    parent = locateAttrParent(rootElem, node);

      }
  else
  {
    parent = node.getParentNode();

    // if((Node.DOCUMENT_NODE != nodeType) && (null == parent))
    // {
    //   throw new RuntimeException("Child does not have parent!");
    // }
  }

  return parent;
}