org.w3c.dom.Document#createAttributeNS ( )源码实例Demo

下面列出了org.w3c.dom.Document#createAttributeNS ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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));
}
 
@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);
	assertXMLEqual("Marshaller writes invalid DOMResult", expected, result);
}
 
源代码3 项目: lams   文件: XMLHelper.java
/**
 * Constructs an attribute owned by the given document with the given name.
 * 
 * @param document the owning document
 * @param namespaceURI the URI for the namespace the attribute is in
 * @param localName the local name
 * @param prefix the prefix of the namespace that attribute is in
 * 
 * @return the constructed attribute
 */
public static Attr constructAttribute(Document document, String namespaceURI, String localName, String prefix) {
    String trimmedLocalName = DatatypeHelper.safeTrimOrNullString(localName);

    if (trimmedLocalName == null) {
        throw new IllegalArgumentException("Local name may not be null or empty");
    }

    String qualifiedName;
    String trimmedPrefix = DatatypeHelper.safeTrimOrNullString(prefix);
    if (trimmedPrefix != null) {
        qualifiedName = trimmedPrefix + ":" + DatatypeHelper.safeTrimOrNullString(trimmedLocalName);
    } else {
        qualifiedName = DatatypeHelper.safeTrimOrNullString(trimmedLocalName);
    }

    if (DatatypeHelper.isEmpty(namespaceURI)) {
        return document.createAttributeNS(null, qualifiedName);
    } else {
        return document.createAttributeNS(namespaceURI, qualifiedName);
    }
}
 
protected Attr getNullNode(Document ownerDocument) {
    if (nullNode == null) {
        try {
            nullNode = ownerDocument.createAttributeNS(
                                Constants.NamespaceSpecNS, XMLNS);
            nullNode.setValue("");
        } catch (Exception e) {
            throw new RuntimeException("Unable to create nullNode: " + e);
        }
    }
    return nullNode;
}
 
源代码5 项目: dragonwell8_jdk   文件: CanonicalizerBase.java
protected Attr getNullNode(Document ownerDocument) {
    if (nullNode == null) {
        try {
            nullNode = ownerDocument.createAttributeNS(
                                Constants.NamespaceSpecNS, XMLNS);
            nullNode.setValue("");
        } catch (Exception e) {
            throw new RuntimeException("Unable to create nullNode: " + e);
        }
    }
    return nullNode;
}
 
源代码6 项目: openjdk-jdk9   文件: DocumentTest.java
@Test
public void testAddNewAttributeNode() throws Exception {
    Document document = createDOMWithNS("DocumentTest01.xml");

    NodeList nodeList = document.getElementsByTagNameNS("http://www.w3.org/TR/REC-html40", "body");
    NodeList childList = nodeList.item(0).getChildNodes();
    Element child = (Element) childList.item(1);
    Attr a = document.createAttributeNS("urn:BooksAreUs.org:BookInfo", "attributeNew");
    child.setAttributeNode(a);
    assertNotNull(child.getAttributeNodeNS("urn:BooksAreUs.org:BookInfo", "attributeNew"));
}
 
源代码7 项目: openjdk-8   文件: CanonicalizerBase.java
protected Attr getNullNode(Document ownerDocument) {
    if (nullNode == null) {
        try {
            nullNode = ownerDocument.createAttributeNS(
                                Constants.NamespaceSpecNS, XMLNS);
            nullNode.setValue("");
        } catch (Exception e) {
            throw new RuntimeException("Unable to create nullNode: " + e);
        }
    }
    return nullNode;
}
 
源代码8 项目: caja   文件: AttrStub.java
Attr toAttr(Document doc, String attrUri, String attrQName) {
  Attr attrNode = doc.createAttributeNS(attrUri, attrQName);
  attrNode.setValue(value);
  Nodes.setFilePositionFor(attrNode, nameTok.pos);
  Nodes.setFilePositionForValue(attrNode, valueTok.pos);
  Nodes.setRawValue(attrNode, valueTok.text);
  return attrNode;
}
 
源代码9 项目: openjdk-8-source   文件: CanonicalizerBase.java
protected Attr getNullNode(Document ownerDocument) {
    if (nullNode == null) {
        try {
            nullNode = ownerDocument.createAttributeNS(
                                Constants.NamespaceSpecNS, XMLNS);
            nullNode.setValue("");
        } catch (Exception e) {
            throw new RuntimeException("Unable to create nullNode: " + e);
        }
    }
    return nullNode;
}
 
源代码10 项目: JDKSourceCode1.8   文件: CanonicalizerBase.java
protected Attr getNullNode(Document ownerDocument) {
    if (nullNode == null) {
        try {
            nullNode = ownerDocument.createAttributeNS(
                                Constants.NamespaceSpecNS, XMLNS);
            nullNode.setValue("");
        } catch (Exception e) {
            throw new RuntimeException("Unable to create nullNode: " + e);
        }
    }
    return nullNode;
}
 
源代码11 项目: openjdk-jdk9   文件: DOMConfigurationTest.java
/**
 * Equivalence class partitioning with state and input values orientation
 * for public void setParameter(String name, Object value) throws
 * DOMException, <br>
 * <b>pre-conditions</b>: the attribute has EntityReference to '&lt;', <br>
 * <b>name</b>: well-formed <br>
 * <b>value</b>: false. <br>
 * <b>Expected results</b>: No error is reported
 */
@Test
public void testWellFormed002() {
    Document doc = null;
    try {
        doc = loadDocument(null, test2_xml);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }

    DOMConfiguration config = doc.getDomConfig();
    if (!config.canSetParameter("well-formed", Boolean.FALSE)) {
        System.out.println("OK, setting 'well-formed' to false is not supported");
        return;
    }
    config.setParameter("well-formed", Boolean.FALSE);

    Element root = doc.getDocumentElement();

    Attr attr = doc.createAttributeNS(null, "attr");
    attr.appendChild(doc.createEntityReference("x"));

    root.setAttributeNode(attr);

    TestHandler testHandler = new TestHandler();
    config.setParameter("error-handler", testHandler);

    doc.normalizeDocument();

    if (testHandler.getError() != null || null != testHandler.getFatalError()) {
        Assert.fail("unexpected error: " + testHandler.getFatalError() + "; " + testHandler.getError());
    }

    return; // Status.passed("OK");

}
 
源代码12 项目: openjdk-jdk9   文件: NamedNodeMapTest.java
@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");
}
 
源代码13 项目: TVRemoteIME   文件: SOAPActionProcessorImpl.java
protected Element writeBodyElement(Document d) {

        Element envelopeElement = d.createElementNS(Constants.SOAP_NS_ENVELOPE, "s:Envelope");
        Attr encodingStyleAttr = d.createAttributeNS(Constants.SOAP_NS_ENVELOPE, "s:encodingStyle");
        encodingStyleAttr.setValue(Constants.SOAP_URI_ENCODING_STYLE);
        envelopeElement.setAttributeNode(encodingStyleAttr);
        d.appendChild(envelopeElement);

        Element bodyElement = d.createElementNS(Constants.SOAP_NS_ENVELOPE, "s:Body");
        envelopeElement.appendChild(bodyElement);

        return bodyElement;
    }
 
源代码14 项目: jdk8u_jdk   文件: CanonicalizerBase.java
protected Attr getNullNode(Document ownerDocument) {
    if (nullNode == null) {
        try {
            nullNode = ownerDocument.createAttributeNS(
                                Constants.NamespaceSpecNS, XMLNS);
            nullNode.setValue("");
        } catch (Exception e) {
            throw new RuntimeException("Unable to create nullNode: " + e);
        }
    }
    return nullNode;
}
 
源代码15 项目: openjdk-jdk8u-backup   文件: CanonicalizerBase.java
protected Attr getNullNode(Document ownerDocument) {
    if (nullNode == null) {
        try {
            nullNode = ownerDocument.createAttributeNS(
                                Constants.NamespaceSpecNS, XMLNS);
            nullNode.setValue("");
        } catch (Exception e) {
            throw new RuntimeException("Unable to create nullNode: " + e);
        }
    }
    return nullNode;
}
 
源代码16 项目: marklogic-contentpump   文件: ElementImpl.java
protected Node cloneNode(Document doc, boolean deep) {
    Element elem = doc.createElementNS(getNamespaceURI(), getTagName());
    elem.setPrefix(getPrefix());

    for (int i = 0; i < attributes.getLength(); i++) {
        Attr attr = (Attr) attributes.item(i);
        if (attr instanceof AttrImpl) {
            elem.setAttributeNode((Attr) ((AttrImpl) attr).cloneNode(doc,
                deep));
        } else {
            // ns decl, stored as Java DOM Attr
            // uri of xmlns is "http://www.w3.org/2000/xmlns/"
            Attr clonedAttr = doc.createAttributeNS(
                "http://www.w3.org/2000/xmlns/", attr.getName());
            clonedAttr.setValue(attr.getValue());
            elem.setAttributeNode(clonedAttr);
        }
    }

    if (deep) {
        // clone children
        NodeList list = getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            NodeImpl n = (NodeImpl) list.item(i);
            Node c = n.cloneNode(doc, true);
            elem.appendChild(c);
        }
    }
    return elem;
}
 
源代码17 项目: caja   文件: DomParser.java
/**
 * Helper method for creating a new attribute with the fixed up namespace
 * name. Ignores DOMException's raised by {@code createAttributeNS()} in case
 * the document being processed is html (removing the attribute that caused
 * the exception), rethrows it as a ParseException otherwise.
 *
 * @param doc The document being parsed.
 * @param attrNsUri The namespace uri for the attribute.
 * @param qname The fully qualified name of the attribute to insert.
 * @param attr The attribute to copy value from.
 * @param el The element to insert the attribute to.
 * @throws ParseException In case of errors.
 */
void createAttributeAndAddToElement(Document doc, String attrNsUri,
                                    String qname, Attr attr, Element el)
    throws ParseException {
  Attr newAttr;
  try {
    newAttr = doc.createAttributeNS(attrNsUri, qname);
  } catch (DOMException e) {
    // Ignore DOMException's like NAMESPACE_ERR if the document being
    // processed is html. Also, remove the associated attribute node.
    if (!asXml) {
      mq.addMessage(DomParserMessageType.IGNORING_TOKEN,
                    Nodes.getFilePositionFor(attr),
                    MessagePart.Factory.valueOf("'" + qname + "'"));
      el.removeAttributeNode(attr);
      return;
    }
    throw new ParseException(new Message(DomParserMessageType.IGNORING_TOKEN,
        Nodes.getFilePositionFor(attr),
        MessagePart.Factory.valueOf("'" + qname + "'")), e);
  }

  newAttr.setValue(attr.getValue());
  if (needsDebugData) {
    Nodes.setFilePositionFor(newAttr, Nodes.getFilePositionFor(attr));
    Nodes.setFilePositionForValue(
        newAttr, Nodes.getFilePositionForValue(attr));
    Nodes.setRawValue(newAttr, Nodes.getRawValue(attr));
  }

  el.removeAttributeNode(attr);
  el.setAttributeNodeNS(newAttr);
}
 
源代码18 项目: hottub   文件: CanonicalizerBase.java
protected Attr getNullNode(Document ownerDocument) {
    if (nullNode == null) {
        try {
            nullNode = ownerDocument.createAttributeNS(
                                Constants.NamespaceSpecNS, XMLNS);
            nullNode.setValue("");
        } catch (Exception e) {
            throw new RuntimeException("Unable to create nullNode: " + e);
        }
    }
    return nullNode;
}
 
源代码19 项目: cxf   文件: PolicyAnnotationListener.java
private Element addPolicy(ServiceInfo service, Policy p, Class<?> cls, String defName) {
    String uri = p.uri();
    String ns = Constants.URI_POLICY_NS;

    if (p.includeInWSDL()) {
        Element element = loadPolicy(uri, defName);
        if (element == null) {
            return null;
        }

        // might have been updated on load policy
        uri = getPolicyId(element);
        ns = element.getNamespaceURI();

        if (service.getDescription() == null && cls != null) {
            service.setDescription(new DescriptionInfo());
            URL u = cls.getResource("/");
            if (u != null) {
                service.getDescription().setBaseURI(u.toString());
            }
        }

        // if not already added to service add it, otherwise ignore
        // and just create the policy reference.
        if (!isExistsPolicy(service.getDescription().getExtensors().get(), uri)) {
            UnknownExtensibilityElement uee = new UnknownExtensibilityElement();
            uee.setElement(element);
            uee.setRequired(true);
            uee.setElementType(DOMUtils.getElementQName(element));
            service.getDescription().addExtensor(uee);
        }

        uri = "#" + uri;
    }

    Document doc = DOMUtils.getEmptyDocument();
    Element el = doc.createElementNS(ns, "wsp:" + Constants.ELEM_POLICY_REF);
    Attr att = doc.createAttributeNS(null, "URI");
    att.setValue(uri);
    el.setAttributeNodeNS(att);
    return el;
}
 
源代码20 项目: javaide   文件: SdkRepoSource.java
/**
 * 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;
}