Java Code Examples for org.w3c.dom.Attr

The following examples show how to use org.w3c.dom.Attr. 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
/** {@inheritDoc} */
protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException {
    EntitiesDescriptor entitiesDescriptor = (EntitiesDescriptor) samlObject;

    if (attribute.getLocalName().equals(EntitiesDescriptor.ID_ATTRIB_NAME)) {
        entitiesDescriptor.setID(attribute.getValue());
        attribute.getOwnerElement().setIdAttributeNode(attribute, true);
    } else if (attribute.getLocalName().equals(TimeBoundSAMLObject.VALID_UNTIL_ATTRIB_NAME)
            && !DatatypeHelper.isEmpty(attribute.getValue())) {
        entitiesDescriptor.setValidUntil(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC()));
    } else if (attribute.getLocalName().equals(CacheableSAMLObject.CACHE_DURATION_ATTRIB_NAME)) {
        entitiesDescriptor.setCacheDuration(new Long(XMLHelper.durationToLong(attribute.getValue())));
    } else if (attribute.getLocalName().equals(EntitiesDescriptor.NAME_ATTRIB_NAME)) {
        entitiesDescriptor.setName(attribute.getValue());
    } else {
        super.processAttribute(samlObject, attribute);
    }
}
 
Example 2
Source Project: jdk8u60   Source File: AbstractDOMParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected Attr createAttrNode (QName attrQName) {
    Attr attr = null;

    if (fNamespaceAware) {
        if (fDocumentImpl != null) {
            // if we are using xerces DOM implementation, call our
            // own constructor to reuse the strings we have here.
            attr = fDocumentImpl.createAttributeNS (attrQName.uri,
            attrQName.rawname,
            attrQName.localpart);
        }
        else {
            attr = fDocument.createAttributeNS (attrQName.uri,
            attrQName.rawname);
        }
    }
    else {
        attr = fDocument.createAttribute (attrQName.rawname);
    }

    return attr;
}
 
Example 3
Source Project: lewis   Source File: LayoutIdFormat.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void visitAttribute(@NonNull XmlContext context, @NonNull Attr attribute) {
    String value = attribute.getValue();

    if (!value.isEmpty()) {

        // Make sure this is really one of the android: attributes
        if (!ANDROID_URI.equals(attribute.getNamespaceURI())) {
            return;
        }

        value = value.substring(5); // ignore "@+id/"

        if (!idCorrectFormat(value)) {
            context.report(ISSUE, attribute, context.getLocation(attribute),
                    String.format("The id \"%1$s\", should be written using lowerCamelCase.", value));
        }

    }
}
 
Example 4
/**
 * Constructor SignatureAlgorithm
 *
 * @param element
 * @param baseURI
 * @param secureValidation
 * @throws XMLSecurityException
 */
public SignatureAlgorithm(
    Element element, String baseURI, boolean secureValidation
) throws XMLSecurityException {
    super(element, baseURI);
    algorithmURI = this.getURI();

    Attr attr = element.getAttributeNodeNS(null, "Id");
    if (attr != null) {
        element.setIdAttributeNode(attr, true);
    }

    if (secureValidation && (XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5.equals(algorithmURI)
        || XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5.equals(algorithmURI))) {
        Object exArgs[] = { algorithmURI };

        throw new XMLSecurityException("signature.signatureAlgorithm", exArgs);
    }

    signatureAlgorithm = getSignatureAlgorithmSpi(algorithmURI);
    signatureAlgorithm.engineGetContextFromElement(this.constructionElement);
}
 
Example 5
public static void test2() {
    String name = "attr";
    String oldValue = "old value";
    String newValue = "new value";
    Attr retAttr;

    IIOMetadataNode parent = new IIOMetadataNode("parent");
    MyAttrNode attrNode1 = new MyAttrNode(name, oldValue);
    MyAttrNode attrNode2 = new MyAttrNode(name, newValue);

    retAttr = parent.setAttributeNode(attrNode1);
    retAttr = parent.setAttributeNode(attrNode2);

    String actName = retAttr.getNodeName();
    String actValue = retAttr.getValue();

    if (!actName.equals(name) || !actValue.equals(oldValue)) {
        throw new RuntimeException("Test 2 failed: Invalid attribute " +
                                   "returned: " +
                                   "(name: " + actName +
                                   ", value: " + actValue + ")");
    }
}
 
Example 6
Source Project: openjdk-8   Source File: NameSpaceSymbTable.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the attribute node that defines the binding for the prefix.
 * @param prefix the prefix to obtain the attribute.
 * @return null if there is no need to render the prefix. Otherwise the node of
 * definition.
 **/
public Attr getMapping(String prefix) {
    NameSpaceSymbEntry entry = symb.get(prefix);
    if (entry == null) {
        //There is no definition for the prefix(a bug?).
        return null;
    }
    if (entry.rendered) {
        //No need to render an entry already rendered.
        return null;
    }
    // Mark this entry as render.
    entry = (NameSpaceSymbEntry) entry.clone();
    needsClone();
    symb.put(prefix, entry);
    entry.rendered = true;
    entry.lastrendered = entry.uri;
    // Return the node for outputing.
    return entry.n;
}
 
Example 7
Source Project: j2objc   Source File: ElementImpl.java    License: Apache License 2.0 6 votes vote down vote up
public Attr setAttributeNode(Attr newAttr) throws DOMException {
    AttrImpl newAttrImpl = (AttrImpl) newAttr;

    if (newAttrImpl.document != this.document) {
        throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, null);
    }

    if (newAttrImpl.getOwnerElement() != null) {
        throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR, null);
    }

    AttrImpl oldAttrImpl = null;

    int i = indexOfAttribute(newAttr.getName());
    if (i != -1) {
        oldAttrImpl = attributes.get(i);
        attributes.remove(i);
    }

    attributes.add(newAttrImpl);
    newAttrImpl.ownerElement = this;

    return oldAttrImpl;
}
 
Example 8
Source Project: knox   Source File: XmlUrlRewriteRulesExporter.java    License: Apache License 2.0 6 votes vote down vote up
private Element createElement( Document document, String name, Object bean )
    throws IntrospectionException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
  Element element = document.createElement( name );
  BeanInfo beanInfo = Introspector.getBeanInfo( bean.getClass(), Object.class );
  for( PropertyDescriptor propInfo: beanInfo.getPropertyDescriptors() ) {
    String propName = propInfo.getName();
    if( propInfo.getReadMethod() != null && String.class.isAssignableFrom( propInfo.getPropertyType() ) ) {
      String propValue = BeanUtils.getProperty( bean, propName );
      if( propValue != null && !propValue.isEmpty() ) {
        // Doing it the hard way to avoid having the &'s in the query string escaped at &
        Attr attr = document.createAttribute( propName );
        attr.setValue( propValue );
        element.setAttributeNode( attr );
        //element.setAttribute( propName, propValue );
      }
    }
  }
  return element;
}
 
Example 9
Source Project: JDKSourceCode1.8   Source File: SignatureProperties.java    License: MIT License 6 votes vote down vote up
/**
 * Constructs {@link SignatureProperties} from {@link Element}
 * @param element <code>SignatureProperties</code> element
 * @param BaseURI the URI of the resource where the XML instance was stored
 * @throws XMLSecurityException
 */
public SignatureProperties(Element element, String BaseURI) throws XMLSecurityException {
    super(element, BaseURI);

    Attr attr = element.getAttributeNodeNS(null, "Id");
    if (attr != null) {
        element.setIdAttributeNode(attr, true);
    }

    int length = getLength();
    for (int i = 0; i < length; i++) {
        Element propertyElem =
            XMLUtils.selectDsNode(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY, i);
        Attr propertyAttr = propertyElem.getAttributeNodeNS(null, "Id");
        if (propertyAttr != null) {
            propertyElem.setIdAttributeNode(propertyAttr, true);
        }
    }
}
 
Example 10
Source Project: astor   Source File: XmlNode.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void addNamespaces(Namespaces rv, Element element) {
    if (element == null) throw new RuntimeException("element must not be null");
    String myDefaultNamespace = toUri(element.lookupNamespaceURI(null));
    String parentDefaultNamespace = "";
    if (element.getParentNode() != null) {
        parentDefaultNamespace = toUri(element.getParentNode().lookupNamespaceURI(null));
    }
    if (!myDefaultNamespace.equals(parentDefaultNamespace) || !(element.getParentNode() instanceof Element) ) {
        rv.declare(Namespace.create("", myDefaultNamespace));
    }
    NamedNodeMap attributes = element.getAttributes();
    for (int i=0; i<attributes.getLength(); i++) {
        Attr attr = (Attr)attributes.item(i);
        if (attr.getPrefix() != null && attr.getPrefix().equals("xmlns")) {
            rv.declare(Namespace.create(attr.getLocalName(), attr.getValue()));
        }
    }
}
 
Example 11
/** {@inheritDoc} */
protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException {
    ContactPerson person = (ContactPerson) samlObject;

    if (attribute.getLocalName().equals(ContactPerson.CONTACT_TYPE_ATTRIB_NAME)) {
        if (ContactPersonTypeEnumeration.TECHNICAL.toString().equals(attribute.getValue())) {
            person.setType(ContactPersonTypeEnumeration.TECHNICAL);
        } else if (ContactPersonTypeEnumeration.SUPPORT.toString().equals(attribute.getValue())) {
            person.setType(ContactPersonTypeEnumeration.SUPPORT);
        } else if (ContactPersonTypeEnumeration.ADMINISTRATIVE.toString().equals(attribute.getValue())) {
            person.setType(ContactPersonTypeEnumeration.ADMINISTRATIVE);
        } else if (ContactPersonTypeEnumeration.BILLING.toString().equals(attribute.getValue())) {
            person.setType(ContactPersonTypeEnumeration.BILLING);
        } else if (ContactPersonTypeEnumeration.OTHER.toString().equals(attribute.getValue())) {
            person.setType(ContactPersonTypeEnumeration.OTHER);
        } else {
            super.processAttribute(samlObject, attribute);
        }
    } else {
        QName attribQName = XMLHelper.getNodeQName(attribute);
        if (attribute.isId()) {
            person.getUnknownAttributes().registerID(attribQName);
        }
        person.getUnknownAttributes().put(attribQName, attribute.getValue());
    }
}
 
Example 12
Source Project: openjdk-8-source   Source File: C14nHelper.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method throws an exception if the Attribute value contains
 * a relative URI.
 *
 * @param attr
 * @throws CanonicalizationException
 */
public static void assertNotRelativeNS(Attr attr) throws CanonicalizationException {
    if (attr == null) {
        return;
    }

    String nodeAttrName = attr.getNodeName();
    boolean definesDefaultNS = nodeAttrName.equals("xmlns");
    boolean definesNonDefaultNS = nodeAttrName.startsWith("xmlns:");

    if ((definesDefaultNS || definesNonDefaultNS) && namespaceIsRelative(attr)) {
        String parentName = attr.getOwnerElement().getTagName();
        String attrValue = attr.getValue();
        Object exArgs[] = { parentName, nodeAttrName, attrValue };

        throw new CanonicalizationException(
            "c14n.Canonicalizer.RelativeNamespace", exArgs
        );
    }
}
 
Example 13
/** {@inheritDoc} */
protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException {

    AuthorizationDecisionStatement authorizationDecisionStatement;
    authorizationDecisionStatement = (AuthorizationDecisionStatement) samlObject;

    if (AuthorizationDecisionStatement.DECISION_ATTRIB_NAME.equals(attribute.getLocalName())) {
        String value = attribute.getValue();
        if (value.equals(DecisionTypeEnumeration.PERMIT.toString())) {
            authorizationDecisionStatement.setDecision(DecisionTypeEnumeration.PERMIT);
        } else if (value.equals(DecisionTypeEnumeration.DENY.toString())) {
            authorizationDecisionStatement.setDecision(DecisionTypeEnumeration.DENY);
        } else if (value.equals(DecisionTypeEnumeration.INDETERMINATE.toString())) {
            authorizationDecisionStatement.setDecision(DecisionTypeEnumeration.INDETERMINATE);
        } else {
            log.error("Unknown value for DecisionType '" + value + "'");
            throw new UnmarshallingException("Unknown value for DecisionType '" + value + "'");
        }
    } else if (AuthorizationDecisionStatement.RESOURCE_ATTRIB_NAME.equals(attribute.getLocalName())) {
        authorizationDecisionStatement.setResource(attribute.getValue());
    } else {
        super.processAttribute(samlObject, attribute);
    }
}
 
Example 14
Source Project: windup   Source File: XmlUtil.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Converts the given {@link Node} to a {@link String}.
 */
public static String nodeToString(Node node)
{
    StringWriter sw = new StringWriter();
    if (node instanceof Attr)
    {
        Attr attr = (Attr) node;
        return attr.getValue();
    }
    try
    {
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        t.setOutputProperty(OutputKeys.INDENT, "no");
        t.transform(new DOMSource(node), new StreamResult(sw));
    }
    catch (TransformerException te)
    {
        LOG.warning("Transformer Exception: " + te.getMessage());
    }
    return sw.toString();
}
 
Example 15
Source Project: Flashtool   Source File: XmlCombiner.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static CombineChildren getCombineChildren(@Nullable Element element) {
	CombineChildren combine = null;
	if (element == null) {
		return null;
	}
	Attr combineAttribute = element.getAttributeNode(CombineChildren.ATTRIBUTE_NAME);
	if (combineAttribute != null) {
		try {
			combine = CombineChildren.valueOf(combineAttribute.getValue().toUpperCase());
		} catch (IllegalArgumentException e) {
			throw new RuntimeException("The attribute 'combine' of element '"
					+ element.getTagName() + "' has invalid value '"
					+ combineAttribute.getValue(), e);
		}
	}
	return combine;
}
 
Example 16
Source Project: openjdk-jdk8u   Source File: Internalizer.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Declares a new prefix on the given element and associates it
 * with the specified namespace URI.
 * <p>
 * Note that this method doesn't use the default namespace
 * even if it can.
 */
private String allocatePrefix( Element e, String nsUri ) {
    // look for existing namespaces.
    NamedNodeMap atts = e.getAttributes();
    for( int i=0; i<atts.getLength(); i++ ) {
        Attr a = (Attr)atts.item(i);
        if( Const.XMLNS_URI.equals(a.getNamespaceURI()) ) {
            if( a.getName().indexOf(':')==-1 )  continue;

            if( a.getValue().equals(nsUri) )
                return a.getLocalName();    // found one
        }
    }

    // none found. allocate new.
    while(true) {
        String prefix = "p"+(int)(Math.random()*1000000)+'_';
        if(e.getAttributeNodeNS(Const.XMLNS_URI,prefix)!=null)
            continue;   // this prefix is already allocated.

        e.setAttributeNS(Const.XMLNS_URI,"xmlns:"+prefix,nsUri);
        return prefix;
    }
}
 
Example 17
Source Project: jdk8u-dev-jdk   Source File: XMLUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method returns the first non-null owner document of the Nodes in this Set.
 * This method is necessary because it <I>always</I> returns a
 * {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE>
 * if the {@link Node} is a {@link Document}.
 *
 * @param xpathNodeSet
 * @return the owner document
 */
public static Document getOwnerDocument(Set<Node> xpathNodeSet) {
    NullPointerException npe = null;
    for (Node node : xpathNodeSet) {
        int nodeType = node.getNodeType();
        if (nodeType == Node.DOCUMENT_NODE) {
            return (Document) node;
        }
        try {
            if (nodeType == Node.ATTRIBUTE_NODE) {
                return ((Attr)node).getOwnerElement().getOwnerDocument();
            }
            return node.getOwnerDocument();
        } catch (NullPointerException e) {
            npe = e;
        }
    }

    throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0")
                                   + " Original message was \""
                                   + (npe == null ? "" : npe.getMessage()) + "\"");
}
 
Example 18
Source Project: hottub   Source File: ElementImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Look up a single Attribute by name. Returns the Attribute's
 * string value, or an empty string (NOT null!) to indicate that the
 * name did not map to a currently defined attribute.
 * <p>
 * Note: Attributes may contain complex node trees. This method
 * returns the "flattened" string obtained from Attribute.getValue().
 * If you need the structure information, see getAttributeNode().
 */
public String getAttribute(String name) {

    if (needsSyncData()) {
        synchronizeData();
    }
    if (attributes == null) {
        return "";
    }
    Attr attr = (Attr)(attributes.getNamedItem(name));
    return (attr == null) ? "" : attr.getValue();

}
 
Example 19
/**
 * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node.
 * @param namespaceURI {@inheritDoc}
 * @param localName {@inheritDoc}
 * @param value {@inheritDoc}
 * @throws javax.xml.stream.XMLStreamException {@inheritDoc}
 */
public void writeAttribute(String namespaceURI,String localName,String value)throws XMLStreamException {
    if(currentNode.getNodeType() == Node.ELEMENT_NODE){
        String prefix = null;
        if(namespaceURI == null ){
            throw new XMLStreamException("NamespaceURI cannot be null");
        }
        if(localName == null){
            throw new XMLStreamException("Local name cannot be null");
        }
        if(namespaceContext != null){
            prefix = namespaceContext.getPrefix(namespaceURI);
        }

        if(prefix == null){
            throw new XMLStreamException("Namespace URI "+namespaceURI +
                    "is not bound to any prefix" );
        }

        String qualifiedName = null;
        if(prefix.equals("")){
            qualifiedName = localName;
        }else{
            qualifiedName = getQName(prefix,localName);
        }
        Attr attr = ownerDoc.createAttributeNS(namespaceURI, qualifiedName);
        attr.setValue(value);
        ((Element)currentNode).setAttributeNode(attr);
    }else{
        //Convert node type to String
        throw new IllegalStateException("Current DOM Node type  is "+ currentNode.getNodeType() +
                "and does not allow attributes to be set ");
    }
}
 
Example 20
/**
 * Creates a DOM Atrribute @see org.w3c.dom.Node and associates it with the current DOM element @see org.w3c.dom.Node.
 * @param localName {@inheritDoc}
 * @param value {@inheritDoc}
 * @throws javax.xml.stream.XMLStreamException {@inheritDoc}
 */
public void writeAttribute(String localName, String value) throws XMLStreamException {

    if(currentNode.getNodeType() == Node.ELEMENT_NODE){
        Attr attr = ownerDoc.createAttribute(localName);
        attr.setValue(value);
        ((Element)currentNode).setAttributeNode(attr);
    }else{
        //Convert node type to String
        throw new IllegalStateException("Current DOM Node type  is "+ currentNode.getNodeType() +
                "and does not allow attributes to be set ");
    }
}
 
Example 21
/**
 * This method is not particularly fast, but shouldn't be called very
 * often. If we start to use it more, we should keep track of the
 * NS declarations using a NamespaceContext implementation instead.
 */
public String getNamespaceURI(String prefix) {
    if (prefix == null) {
        throw new IllegalArgumentException("DOMStreamReader: getNamespaceURI(String) call with a null prefix");
    }
    else if (prefix.equals("xml")) {
        return "http://www.w3.org/XML/1998/namespace";
    }
    else if (prefix.equals("xmlns")) {
        return "http://www.w3.org/2000/xmlns/";
    }

    // check scopes
    String nsUri = scopes[depth].getNamespaceURI(prefix);
    if(nsUri!=null)    return nsUri;

    // then ancestors above start node
    Node node = findRootElement();
    String nsDeclName = prefix.length()==0 ? "xmlns" : "xmlns:"+prefix;
    while (node.getNodeType() != DOCUMENT_NODE) {
        // Is ns declaration on this element?
        NamedNodeMap namedNodeMap = node.getAttributes();
        Attr attr = (Attr) namedNodeMap.getNamedItem(nsDeclName);
        if (attr != null)
            return attr.getValue();
        node = node.getParentNode();
    }
    return null;
}
 
Example 22
/**
 * Called when the current node is {@link Element} to look at attribute list
 * (which contains both ns decl and attributes in DOM) and split them
 * to attributes-proper and namespace decls.
 */
protected void splitAttributes() {
    // Clear attribute and namespace lists
    _currentAttributes.clear();

    Scope scope = allocateScope();

    _namedNodeMap = _current.getAttributes();
    if (_namedNodeMap != null) {
        final int n = _namedNodeMap.getLength();
        for (int i = 0; i < n; i++) {
            final Attr attr = (Attr) _namedNodeMap.item(i);
            final String attrName = attr.getNodeName();
            if (attrName.startsWith("xmlns:") || attrName.equals("xmlns")) {     // NS decl?
                scope.currentNamespaces.add(attr);
            }
            else {
                _currentAttributes.add(attr);
            }
        }
    }

    // verify that all the namespaces used in element and attributes are indeed available
    ensureNs(_current);
    for( int i=_currentAttributes.size()-1; i>=0; i-- ) {
        Attr a = _currentAttributes.get(i);
        if(fixNull(a.getNamespaceURI()).length()>0)
            ensureNs(a);    // no need to declare "" for attributes in the default namespace
    }
}
 
Example 23
void getXmlnsAttr(Collection<Attr> col) {
    int size = levels.size() - 1;
    if (cur == null) {
        cur = new XmlsStackElement();
        cur.level = currentLevel;
        lastlevel = currentLevel;
        levels.add(cur);
    }
    boolean parentRendered = false;
    XmlsStackElement e = null;
    if (size == -1) {
        parentRendered = true;
    } else {
        e = levels.get(size);
        if (e.rendered && e.level + 1 == currentLevel) {
            parentRendered = true;
        }
    }
    if (parentRendered) {
        col.addAll(cur.nodes);
        cur.rendered = true;
        return;
    }

    Map<String, Attr> loa = new HashMap<String, Attr>();
    for (; size >= 0; size--) {
        e = levels.get(size);
        Iterator<Attr> it = e.nodes.iterator();
        while (it.hasNext()) {
            Attr n = it.next();
            if (!loa.containsKey(n.getName())) {
                loa.put(n.getName(), n);
            }
        }
    }

    cur.rendered = true;
    col.addAll(loa.values());
}
 
Example 24
Source Project: netbeans   Source File: Hk2DatasourceManager.java    License: Apache License 2.0 5 votes vote down vote up
private static void appendAttr(Document doc, Node node, String name, String value, boolean force) {
    if(force || (name != null && name.length() > 0)) {
        Attr attr = doc.createAttribute(name);
        attr.setValue(value);
        NamedNodeMap attrs = node.getAttributes();
        attrs.setNamedItem(attr);
    }
}
 
Example 25
Source Project: JDKSourceCode1.8   Source File: ElementImpl.java    License: 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 26
Source Project: fastods   Source File: AttrList.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param attributes the attributes
 * @return the attr list
 */
static AttrList create(final NamedNodeMap attributes) {
    final int l = attributes.getLength();
    final List<Attr> as = new ArrayList<Attr>(l);
    for (int i = 0; i < l; i++) {
        as.add((Attr) attributes.item(i));
    }
    return new AttrList(as);
}
 
Example 27
private void addNamespaces(Node element) {
    if (element.getParentNode() != null) {
        addNamespaces(element.getParentNode());
    }
    if (element instanceof Element) {
        Element el = (Element)element;
        NamedNodeMap map = el.getAttributes();
        for (int x = 0; x < map.getLength(); x++) {
            Attr attr = (Attr)map.item(x);
            if ("xmlns".equals(attr.getPrefix())) {
                namespaceMap.put(attr.getLocalName(), attr.getValue());
            }
        }
    }
}
 
Example 28
/** {@inheritDoc} */
protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException {
    SignatureConfirmation sc = (SignatureConfirmation) xmlObject;
    
    QName attrName =
        XMLHelper.constructQName(attribute.getNamespaceURI(), attribute.getLocalName(), attribute.getPrefix());
    if (SignatureConfirmation.WSU_ID_ATTR_NAME.equals(attrName)) {
        sc.setWSUId(attribute.getValue());
        attribute.getOwnerElement().setIdAttributeNode(attribute, true);
    } else if (SignatureConfirmation.VALUE_ATTRIB_NAME.equals(attribute.getLocalName())) {
        sc.setValue(attribute.getValue());
    } else {
        super.processAttribute(xmlObject, attribute);
    }
}
 
Example 29
@Test
public void testSetNamedItemNS() throws Exception {
    final String nsURI = "urn:BooksAreUs.org:BookInfo";
    Document document = createDOMWithNS("NamedNodeMap01.xml");
    NodeList nodeList = document.getElementsByTagName("body");
    nodeList = nodeList.item(0).getChildNodes();
    Node n = nodeList.item(3);

    NamedNodeMap namedNodeMap = n.getAttributes();

    // creating an Attribute using createAttributeNS
    // method having the same namespaceURI
    // and the same qualified name as the existing one in the xml file
    Attr attr = document.createAttributeNS(nsURI, "b:style");
    // setting to a new Value
    attr.setValue("newValue");
    Node replacedAttr = namedNodeMap.setNamedItemNS(attr); // return the replaced attr
    assertEquals(replacedAttr.getNodeValue(), "font-family");
    Node updatedAttr = namedNodeMap.getNamedItemNS(nsURI, "style");
    assertEquals(updatedAttr.getNodeValue(), "newValue");


    // creating a non existing attribute node
    attr = document.createAttributeNS(nsURI, "b:newNode");
    attr.setValue("newValue");

    assertNull(namedNodeMap.setNamedItemNS(attr)); // return null

    // checking if the node could be accessed
    // using the getNamedItemNS method
    Node newAttr = namedNodeMap.getNamedItemNS(nsURI, "newNode");
    assertEquals(newAttr.getNodeValue(), "newValue");
}
 
Example 30
Source Project: jdk1.8-source-analysis   Source File: ElementImpl.java    License: Apache License 2.0 5 votes vote down vote up
public Attr getAttributeNodeNS(String namespaceURI, String localName) {
    for (int i=0; i<attrs.length; i++) {
        if (attrs[i].getName().equals(localName) && nsEquals(attrs[i].getNamespaceURI(), namespaceURI)) {
            return attrs[i];
        }
    }
    return null;
}