Java Code Examples for org.w3c.dom.Attr#setNodeValue()

The following examples show how to use org.w3c.dom.Attr#setNodeValue() . 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
Source File: AbstractMarshallerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void marshalEmptyDOMResult() throws Exception {
	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
	documentBuilderFactory.setNamespaceAware(true);
	DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
	DOMResult domResult = new DOMResult();
	marshaller.marshal(flights, domResult);
	assertTrue("DOMResult does not contain a Document", domResult.getNode() instanceof Document);
	Document result = (Document) domResult.getNode();
	Document expected = builder.newDocument();
	Element flightsElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flights");
	Attr namespace = expected.createAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:tns");
	namespace.setNodeValue("http://samples.springframework.org/flight");
	flightsElement.setAttributeNode(namespace);
	expected.appendChild(flightsElement);
	Element flightElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flight");
	flightsElement.appendChild(flightElement);
	Element numberElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:number");
	flightElement.appendChild(numberElement);
	Text text = expected.createTextNode("42");
	numberElement.appendChild(text);
	assertThat("Marshaller writes invalid DOMResult", result, isSimilarTo(expected));
}
 
Example 2
Source File: AbstractMarshallerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void marshalDOMResult() throws Exception {
	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
	documentBuilderFactory.setNamespaceAware(true);
	DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
	Document result = builder.newDocument();
	DOMResult domResult = new DOMResult(result);
	marshaller.marshal(flights, domResult);
	Document expected = builder.newDocument();
	Element flightsElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flights");
	Attr namespace = expected.createAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:tns");
	namespace.setNodeValue("http://samples.springframework.org/flight");
	flightsElement.setAttributeNode(namespace);
	expected.appendChild(flightsElement);
	Element flightElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flight");
	flightsElement.appendChild(flightElement);
	Element numberElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:number");
	flightElement.appendChild(numberElement);
	Text text = expected.createTextNode("42");
	numberElement.appendChild(text);
	assertThat("Marshaller writes invalid DOMResult", result, isSimilarTo(expected));
}
 
Example 3
Source File: AbstractMarshallerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void marshalDOMResult() throws Exception {
	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
	documentBuilderFactory.setNamespaceAware(true);
	DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
	Document result = builder.newDocument();
	DOMResult domResult = new DOMResult(result);
	marshaller.marshal(flights, domResult);
	Document expected = builder.newDocument();
	Element flightsElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flights");
	Attr namespace = expected.createAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:tns");
	namespace.setNodeValue("http://samples.springframework.org/flight");
	flightsElement.setAttributeNode(namespace);
	expected.appendChild(flightsElement);
	Element flightElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flight");
	flightsElement.appendChild(flightElement);
	Element numberElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:number");
	flightElement.appendChild(numberElement);
	Text text = expected.createTextNode("42");
	numberElement.appendChild(text);
	assertThat("Marshaller writes invalid DOMResult", result, isSimilarTo(expected));
}
 
Example 4
Source File: AbstractMarshallerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void marshalDOMResult() throws Exception {
	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
	documentBuilderFactory.setNamespaceAware(true);
	DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
	Document result = builder.newDocument();
	DOMResult domResult = new DOMResult(result);
	marshaller.marshal(flights, domResult);
	Document expected = builder.newDocument();
	Element flightsElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flights");
	Attr namespace = expected.createAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:tns");
	namespace.setNodeValue("http://samples.springframework.org/flight");
	flightsElement.setAttributeNode(namespace);
	expected.appendChild(flightsElement);
	Element flightElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flight");
	flightsElement.appendChild(flightElement);
	Element numberElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:number");
	flightElement.appendChild(numberElement);
	Text text = expected.createTextNode("42");
	numberElement.appendChild(text);
	assertXMLEqual("Marshaller writes invalid DOMResult", expected, result);
}
 
Example 5
Source File: ElementImpl.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
* Add a new name/value pair, or replace the value of the existing
* attribute having that name.
*
* Note: this method supports only the simplest kind of Attribute,
* one whose value is a string contained in a single Text node.
* If you want to assert a more complex value (which XML permits,
* though HTML doesn't), see setAttributeNode().
*
* The attribute is created with specified=true, meaning it's an
* explicit value rather than inherited from the DTD as a default.
* Again, setAttributeNode can be used to achieve other results.
*
* @throws DOMException(INVALID_NAME_ERR) if the name is not acceptable.
* (Attribute factory will do that test for us.)
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if the node is
* readonly.
*/
   public void setAttribute(String name, String value) {

           if (ownerDocument.errorChecking && isReadOnly()) {
                   String msg =
                           DOMMessageFormatter.formatMessage(
                                   DOMMessageFormatter.DOM_DOMAIN,
                                   "NO_MODIFICATION_ALLOWED_ERR",
                                   null);
                   throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg);
           }

           if (needsSyncData()) {
                   synchronizeData();
           }

           Attr newAttr = getAttributeNode(name);
           if (newAttr == null) {
                   newAttr = getOwnerDocument().createAttribute(name);

                   if (attributes == null) {
                           attributes = new AttributeMap(this, null);
                   }

                   newAttr.setNodeValue(value);
                   attributes.setNamedItem(newAttr);
           }
           else {
                   newAttr.setNodeValue(value);
           }

   }
 
Example 6
Source File: ElementImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
* Add a new name/value pair, or replace the value of the existing
* attribute having that name.
*
* Note: this method supports only the simplest kind of Attribute,
* one whose value is a string contained in a single Text node.
* If you want to assert a more complex value (which XML permits,
* though HTML doesn't), see setAttributeNode().
*
* The attribute is created with specified=true, meaning it's an
* explicit value rather than inherited from the DTD as a default.
* Again, setAttributeNode can be used to achieve other results.
*
* @throws DOMException(INVALID_NAME_ERR) if the name is not acceptable.
* (Attribute factory will do that test for us.)
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if the node is
* readonly.
*/
   public void setAttribute(String name, String value) {

           if (ownerDocument.errorChecking && isReadOnly()) {
                   String msg =
                           DOMMessageFormatter.formatMessage(
                                   DOMMessageFormatter.DOM_DOMAIN,
                                   "NO_MODIFICATION_ALLOWED_ERR",
                                   null);
                   throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg);
           }

           if (needsSyncData()) {
                   synchronizeData();
           }

           Attr newAttr = getAttributeNode(name);
           if (newAttr == null) {
                   newAttr = getOwnerDocument().createAttribute(name);

                   if (attributes == null) {
                           attributes = new AttributeMap(this, null);
                   }

                   newAttr.setNodeValue(value);
                   attributes.setNamedItem(newAttr);
           }
           else {
                   newAttr.setNodeValue(value);
           }

   }
 
Example 7
Source File: ElementImpl.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
* Add a new name/value pair, or replace the value of the existing attribute
* having that name.
*
* Note: this method supports only the simplest kind of Attribute, one whose
* value is a string contained in a single Text node. If you want to assert
* a more complex value (which XML permits, though HTML doesn't), see
* setAttributeNode().
*
* The attribute is created with specified=true, meaning it's an explicit
* value rather than inherited from the DTD as a default. Again,
* setAttributeNode can be used to achieve other results.
*
* @throws DOMException(INVALID_NAME_ERR) if the name is not acceptable.
* (Attribute factory will do that test for us.)
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if the node is
* readonly.
*/
   public void setAttribute(String name, String value) {

           if (ownerDocument.errorChecking && isReadOnly()) {
               String msg = DOMMessageFormatter.formatMessage(
                                   DOMMessageFormatter.DOM_DOMAIN,
                                   "NO_MODIFICATION_ALLOWED_ERR",
                                   null);
               throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg);
           }

           if (needsSyncData()) {
                   synchronizeData();
           }

           Attr newAttr = getAttributeNode(name);
           if (newAttr == null) {
                   newAttr = getOwnerDocument().createAttribute(name);

                   if (attributes == null) {
                           attributes = new AttributeMap(this, null);
                   }

                   newAttr.setNodeValue(value);
                   attributes.setNamedItem(newAttr);
           } else {
                   newAttr.setNodeValue(value);
           }

   }
 
Example 8
Source File: NodeCreateRule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adds a new child {@link org.w3c.dom.Element Element} to the current
 * node.
 * 
 * @param namespaceURI the namespace URI
 * @param localName the local name
 * @param qName the qualified (prefixed) name
 * @param atts the list of attributes
 * @throws SAXException if the DOM implementation throws an exception
 */
@Override
public void startElement(String namespaceURI, String localName,
                         String qName, Attributes atts)
    throws SAXException {

    addTextIfPresent();

    try {
        Node previousTop = top;
        if ((localName == null) || (localName.length() == 0)) { 
            top = doc.createElement(qName);
        } else {
            top = doc.createElementNS(namespaceURI, localName);
        }
        for (int i = 0; i < atts.getLength(); i++) {
            Attr attr = null;
            if ((atts.getLocalName(i) == null) ||
                (atts.getLocalName(i).length() == 0)) {
                attr = doc.createAttribute(atts.getQName(i));
                attr.setNodeValue(atts.getValue(i));
                ((Element)top).setAttributeNode(attr);
            } else {
                attr = doc.createAttributeNS(atts.getURI(i),
                                             atts.getLocalName(i));
                attr.setNodeValue(atts.getValue(i));
                ((Element)top).setAttributeNodeNS(attr);
            }
        }
        previousTop.appendChild(top);
        depth++;
    } catch (DOMException e) {
        throw new SAXException(e.getMessage());
    }

}
 
Example 9
Source File: NodeCreateRule.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a new child {@link org.w3c.dom.Element Element} to the current
 * node.
 * 
 * @param namespaceURI the namespace URI
 * @param localName the local name
 * @param qName the qualified (prefixed) name
 * @param atts the list of attributes
 * @throws SAXException if the DOM implementation throws an exception
 */
@Override
public void startElement(String namespaceURI, String localName,
                         String qName, Attributes atts)
    throws SAXException {

    try {
        Node previousTop = top;
        if ((localName == null) || (localName.length() == 0)) { 
            top = doc.createElement(qName);
        } else {
            top = doc.createElementNS(namespaceURI, localName);
        }
        for (int i = 0; i < atts.getLength(); i++) {
            Attr attr = null;
            if ((atts.getLocalName(i) == null) ||
                (atts.getLocalName(i).length() == 0)) {
                attr = doc.createAttribute(atts.getQName(i));
                attr.setNodeValue(atts.getValue(i));
                ((Element)top).setAttributeNode(attr);
            } else {
                attr = doc.createAttributeNS(atts.getURI(i),
                                             atts.getLocalName(i));
                attr.setNodeValue(atts.getValue(i));
                ((Element)top).setAttributeNodeNS(attr);
            }
        }
        previousTop.appendChild(top);
        depth++;
    } catch (DOMException e) {
        throw new SAXException(e.getMessage(), e);
    }

}
 
Example 10
Source File: ElementImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
* Add a new name/value pair, or replace the value of the existing
* attribute having that name.
*
* Note: this method supports only the simplest kind of Attribute,
* one whose value is a string contained in a single Text node.
* If you want to assert a more complex value (which XML permits,
* though HTML doesn't), see setAttributeNode().
*
* The attribute is created with specified=true, meaning it's an
* explicit value rather than inherited from the DTD as a default.
* Again, setAttributeNode can be used to achieve other results.
*
* @throws DOMException(INVALID_NAME_ERR) if the name is not acceptable.
* (Attribute factory will do that test for us.)
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if the node is
* readonly.
*/
   public void setAttribute(String name, String value) {

           if (ownerDocument.errorChecking && isReadOnly()) {
                   String msg =
                           DOMMessageFormatter.formatMessage(
                                   DOMMessageFormatter.DOM_DOMAIN,
                                   "NO_MODIFICATION_ALLOWED_ERR",
                                   null);
                   throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg);
           }

           if (needsSyncData()) {
                   synchronizeData();
           }

           Attr newAttr = getAttributeNode(name);
           if (newAttr == null) {
                   newAttr = getOwnerDocument().createAttribute(name);

                   if (attributes == null) {
                           attributes = new AttributeMap(this, null);
                   }

                   newAttr.setNodeValue(value);
                   attributes.setNamedItem(newAttr);
           }
           else {
                   newAttr.setNodeValue(value);
           }

   }
 
Example 11
Source File: TGBrowserWriter.java    From tuxguitar with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void saveCollections(TGBrowserManager manager, Document document){
	//chords tag
	Node listNode = document.createElement(ITEM_LIST_TAG);
	
	Iterator<TGBrowserCollection> collections = manager.getCollections();
	while(collections.hasNext()){
		TGBrowserCollection collection = (TGBrowserCollection)collections.next();
		
		//collection tag
		Node node = document.createElement(ITEM_TAG);
		listNode.appendChild(node);
		
		//type attribute
		Attr typeAttr = document.createAttribute(ATTRIBUTE_TYPE);
		typeAttr.setNodeValue(collection.getType());
		
		//title attribute
		Attr titleAttr = document.createAttribute(ATTRIBUTE_TITLE);
		titleAttr.setNodeValue(collection.getData().getTitle());
		
		//data attribute
		Attr dataAttr = document.createAttribute(ATTRIBUTE_DATA);
		dataAttr.setNodeValue(collection.getData().getData());
		
		node.getAttributes().setNamedItem(typeAttr);
		node.getAttributes().setNamedItem(titleAttr);
		node.getAttributes().setNamedItem(dataAttr);
	}
	
	document.appendChild(listNode);
}
 
Example 12
Source File: QualifyingPropertyVerificationContext.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
private <TObj> TObj getReferencedElement(
        String objReference,
        Map<Element, TObj> mapper)
{
    if (!objReference.startsWith("#"))
        throw new IllegalArgumentException();

    if (mapper.isEmpty())
        return null;

    // A little workaround to be able to use the ResourceResolver.
    Attr refAttr = this.signatureDoc.createAttributeNS(null, "ref");
    refAttr.setNodeValue(objReference);
    this.signatureDoc.createElementNS(null, "dummy").setAttributeNodeNS(refAttr);

    try
    {
        XMLSignatureInput refData = ResourceResolver.getInstance(refAttr, "", true).resolve(refAttr, "", true);
        // This has to be a NodeSet data because it is a same-document reference.
        Node refNode = refData.getSubNode();
        if (refNode.getNodeType() != Node.ELEMENT_NODE)
            return null;
        // May return null.
        return mapper.get((Element)refNode);
    } catch (ResourceResolverException ex)
    {
        // Maybe an exception should be thrown...
        return null;
    }
}
 
Example 13
Source File: ElementImpl.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
* Add a new name/value pair, or replace the value of the existing
* attribute having that name.
*
* Note: this method supports only the simplest kind of Attribute,
* one whose value is a string contained in a single Text node.
* If you want to assert a more complex value (which XML permits,
* though HTML doesn't), see setAttributeNode().
*
* The attribute is created with specified=true, meaning it's an
* explicit value rather than inherited from the DTD as a default.
* Again, setAttributeNode can be used to achieve other results.
*
* @throws DOMException(INVALID_NAME_ERR) if the name is not acceptable.
* (Attribute factory will do that test for us.)
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if the node is
* readonly.
*/
   public void setAttribute(String name, String value) {

           if (ownerDocument.errorChecking && isReadOnly()) {
                   String msg =
                           DOMMessageFormatter.formatMessage(
                                   DOMMessageFormatter.DOM_DOMAIN,
                                   "NO_MODIFICATION_ALLOWED_ERR",
                                   null);
                   throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg);
           }

           if (needsSyncData()) {
                   synchronizeData();
           }

           Attr newAttr = getAttributeNode(name);
           if (newAttr == null) {
                   newAttr = getOwnerDocument().createAttribute(name);

                   if (attributes == null) {
                           attributes = new AttributeMap(this, null);
                   }

                   newAttr.setNodeValue(value);
                   attributes.setNamedItem(newAttr);
           }
           else {
                   newAttr.setNodeValue(value);
           }

   }
 
Example 14
Source File: NodeCreateRule.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a new child {@link org.w3c.dom.Element Element} to the current
 * node.
 * 
 * @param namespaceURI the namespace URI
 * @param localName the local name
 * @param qName the qualified (prefixed) name
 * @param atts the list of attributes
 * @throws SAXException if the DOM implementation throws an exception
 */
@Override
public void startElement(String namespaceURI, String localName,
                         String qName, Attributes atts)
    throws SAXException {

    try {
        Node previousTop = top;
        if ((localName == null) || (localName.length() == 0)) { 
            top = doc.createElement(qName);
        } else {
            top = doc.createElementNS(namespaceURI, localName);
        }
        for (int i = 0; i < atts.getLength(); i++) {
            Attr attr = null;
            if ((atts.getLocalName(i) == null) ||
                (atts.getLocalName(i).length() == 0)) {
                attr = doc.createAttribute(atts.getQName(i));
                attr.setNodeValue(atts.getValue(i));
                ((Element)top).setAttributeNode(attr);
            } else {
                attr = doc.createAttributeNS(atts.getURI(i),
                                             atts.getLocalName(i));
                attr.setNodeValue(atts.getValue(i));
                ((Element)top).setAttributeNodeNS(attr);
            }
        }
        previousTop.appendChild(top);
        depth++;
    } catch (DOMException e) {
        throw new SAXException(e.getMessage(), e);
    }

}
 
Example 15
Source File: ElementImpl.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
* Add a new name/value pair, or replace the value of the existing
* attribute having that name.
*
* Note: this method supports only the simplest kind of Attribute,
* one whose value is a string contained in a single Text node.
* If you want to assert a more complex value (which XML permits,
* though HTML doesn't), see setAttributeNode().
*
* The attribute is created with specified=true, meaning it's an
* explicit value rather than inherited from the DTD as a default.
* Again, setAttributeNode can be used to achieve other results.
*
* @throws DOMException(INVALID_NAME_ERR) if the name is not acceptable.
* (Attribute factory will do that test for us.)
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if the node is
* readonly.
*/
   public void setAttribute(String name, String value) {

           if (ownerDocument.errorChecking && isReadOnly()) {
                   String msg =
                           DOMMessageFormatter.formatMessage(
                                   DOMMessageFormatter.DOM_DOMAIN,
                                   "NO_MODIFICATION_ALLOWED_ERR",
                                   null);
                   throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg);
           }

           if (needsSyncData()) {
                   synchronizeData();
           }

           Attr newAttr = getAttributeNode(name);
           if (newAttr == null) {
                   newAttr = getOwnerDocument().createAttribute(name);

                   if (attributes == null) {
                           attributes = new AttributeMap(this, null);
                   }

                   newAttr.setNodeValue(value);
                   attributes.setNamedItem(newAttr);
           }
           else {
                   newAttr.setNodeValue(value);
           }

   }
 
Example 16
Source File: XmlUtilities.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void appendAttribute(Element baseNode, String attributeName, String attributeValue) {
	Attr typeAttribute = baseNode.getOwnerDocument().createAttribute(attributeName);
	if (attributeValue == null) {
		typeAttribute.setNodeValue("<null>");
	} else {
		typeAttribute.setNodeValue(attributeValue);
	}
	baseNode.setAttributeNode(typeAttribute);
}
 
Example 17
Source File: ElementImpl.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
* Add a new name/value pair, or replace the value of the existing
* attribute having that name.
*
* Note: this method supports only the simplest kind of Attribute,
* one whose value is a string contained in a single Text node.
* If you want to assert a more complex value (which XML permits,
* though HTML doesn't), see setAttributeNode().
*
* The attribute is created with specified=true, meaning it's an
* explicit value rather than inherited from the DTD as a default.
* Again, setAttributeNode can be used to achieve other results.
*
* @throws DOMException(INVALID_NAME_ERR) if the name is not acceptable.
* (Attribute factory will do that test for us.)
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if the node is
* readonly.
*/
   public void setAttribute(String name, String value) {

           if (ownerDocument.errorChecking && isReadOnly()) {
                   String msg =
                           DOMMessageFormatter.formatMessage(
                                   DOMMessageFormatter.DOM_DOMAIN,
                                   "NO_MODIFICATION_ALLOWED_ERR",
                                   null);
                   throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, msg);
           }

           if (needsSyncData()) {
                   synchronizeData();
           }

           Attr newAttr = getAttributeNode(name);
           if (newAttr == null) {
                   newAttr = getOwnerDocument().createAttribute(name);

                   if (attributes == null) {
                           attributes = new AttributeMap(this, null);
                   }

                   newAttr.setNodeValue(value);
                   attributes.setNamedItem(newAttr);
           }
           else {
                   newAttr.setNodeValue(value);
           }

   }
 
Example 18
Source File: MusicXMLWriter.java    From tuxguitar with GNU Lesser General Public License v2.1 4 votes vote down vote up
private Node addAttribute(Node node, String name, String value){
	Attr attribute = this.document.createAttribute(name);
	attribute.setNodeValue(value);
	node.getAttributes().setNamedItem(attribute);
	return node;
}
 
Example 19
Source File: ManifestMerger.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Extracts the fully qualified class names from the manifest and uses the
 * prefix notation relative to the manifest package. This basically reverses
 * the effects of {@link #expandFqcns(Document)}, though of course it may
 * also remove prefixes which were inlined in the original documents.
 *
 * @param doc the document in which to extract the FQCNs.
 */
private void extractFqcns(Document doc) {
    // Find the package attribute of the manifest.
    String pkg = null;
    Element manifest = findFirstElement(doc, "/manifest");
    if (manifest != null) {
        pkg = manifest.getAttribute("package");
    }

    if (pkg == null || pkg.isEmpty()) {
        return;
    }

    int pkgLength = pkg.length();
    for (String elementAttr : sClassAttributes) {
        String[] names = elementAttr.split("/");
        if (names.length != 2) {
            continue;
        }
        String elemName = names[0];
        String attrName = names[1];
        NodeList elements = doc.getElementsByTagName(elemName);
        for (int i = 0; i < elements.getLength(); i++) {
            Node elem = elements.item(i);
            if (elem instanceof Element) {
                Attr attr = ((Element) elem).getAttributeNodeNS(NS_URI, attrName);
                if (attr != null) {
                    String value = attr.getNodeValue();

                    // We know it's a shortened FQCN if it starts with a dot
                    // or does not contain any dot.
                    if (value != null && value.length() > pkgLength &&
                            value.startsWith(pkg) && value.charAt(pkgLength) == '.') {
                        value = value.substring(pkgLength);
                        attr.setNodeValue(value);
                    }
                }
            }
        }
    }
}
 
Example 20
Source File: SdkRepoSource.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Helper method used by {@link #findAlternateToolsXml(InputStream)} to duplicate a node
 * and attach it to the given root in the new document.
 */
private Element duplicateNode(Element newRootNode, Element oldNode,
        String namespaceUri, String prefix) {
    // The implementation here is more or less equivalent to
    //
    //    newRoot.appendChild(newDoc.importNode(oldNode, deep=true))
    //
    // except we can't just use importNode() since we need to deal with the fact
    // that the old document is not namespace-aware yet the new one is.

    Document newDoc = newRootNode.getOwnerDocument();
    Element newNode = null;

    String nodeName = oldNode.getNodeName();
    int pos = nodeName.indexOf(':');
    if (pos > 0 && pos < nodeName.length() - 1) {
        nodeName = nodeName.substring(pos + 1);
        newNode = newDoc.createElementNS(namespaceUri, nodeName);
        newNode.setPrefix(prefix);
    } else {
        newNode = newDoc.createElement(nodeName);
    }

    newRootNode.appendChild(newNode);

    // Merge in all the attributes
    NamedNodeMap attrs = oldNode.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        Attr attr = (Attr) attrs.item(i);
        Attr newAttr = null;

        String attrName = attr.getNodeName();
        pos = attrName.indexOf(':');
        if (pos > 0 && pos < attrName.length() - 1) {
            attrName = attrName.substring(pos + 1);
            newAttr = newDoc.createAttributeNS(namespaceUri, attrName);
            newAttr.setPrefix(prefix);
        } else {
            newAttr = newDoc.createAttribute(attrName);
        }

        newAttr.setNodeValue(attr.getNodeValue());

        if (pos > 0) {
            newNode.getAttributes().setNamedItemNS(newAttr);
        } else {
            newNode.getAttributes().setNamedItem(newAttr);
        }
    }

    // Merge all child elements and texts
    for (Node child = oldNode.getFirstChild(); child != null; child = child.getNextSibling()) {
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            duplicateNode(newNode, (Element) child, namespaceUri, prefix);

        } else if (child.getNodeType() == Node.TEXT_NODE) {
            Text newText = newDoc.createTextNode(child.getNodeValue());
            newNode.appendChild(newText);
        }
    }

    return newNode;
}