下面列出了org.w3c.dom.NamedNodeMap#getNamedItemNS ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static boolean compareElementAttrs(Element e1, Element e2) {
NamedNodeMap at1 = e1.getAttributes();
NamedNodeMap at2 = e2.getAttributes();
if (at1.getLength() != at2.getLength()) {
System.out.println("Different number of attributes");
}
for (int i = 0; i < at1.getLength(); i++) {
Attr attr1 = (Attr)at1.item(i);
Attr attr2 = (Attr)at2.getNamedItemNS(attr1.getNamespaceURI(), attr1.getLocalName());
if (attr2 == null) {
System.out.println("Attribute " + attr1.getNodeName() + " not found");
return false;
}
if (!compareStrings(attr1.getNodeValue(), attr2.getNodeValue())) {
System.out.println("Different attributes " + attr1.getNodeName() + " and " + attr2.getNodeName());
return false;
}
}
return true;
}
/**
* Separates XML namespace related attributes from "normal" attributes.xb
*/
private Attributes splitAttributes(final NamedNodeMap map) {
Attr sLoc = (Attr) map.getNamedItemNS(XMLConstants
.W3C_XML_SCHEMA_INSTANCE_NS_URI,
"schemaLocation");
Attr nNsLoc = (Attr) map.getNamedItemNS(XMLConstants
.W3C_XML_SCHEMA_INSTANCE_NS_URI,
"noNamespaceSchemaLocation");
Attr type = (Attr) map.getNamedItemNS(XMLConstants
.W3C_XML_SCHEMA_INSTANCE_NS_URI,
"type");
List<Attr> rest = new LinkedList<Attr>();
final int len = map.getLength();
for (int i = 0; i < len; i++) {
Attr a = (Attr) map.item(i);
if (!XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(a.getNamespaceURI())
&& a != sLoc && a != nNsLoc && a != type
&& getAttributeFilter().test(a)) {
rest.add(a);
}
}
return new Attributes(sLoc, nNsLoc, type, rest);
}
/**
* Checks whether the given element has a tools:merge=override or tools:merge=remove attribute.
* @param node The node to check.
* @return True if the element has a tools:merge=override or tools:merge=remove attribute.
*/
private boolean hasOverrideOrRemoveTag(@Nullable Node node) {
if (node == null || node.getNodeType() != Node.ELEMENT_NODE) {
return false;
}
NamedNodeMap attrs = node.getAttributes();
Node merge = attrs.getNamedItemNS(TOOLS_URI, MERGE_ATTR);
String value = merge == null ? null : merge.getNodeValue();
return MERGE_OVERRIDE.equals(value) || MERGE_REMOVE.equals(value);
}
/**
* Checks whether the given element has a tools:merge=override or tools:merge=remove attribute.
* @param node The node to check.
* @return True if the element has a tools:merge=override or tools:merge=remove attribute.
*/
private boolean hasOverrideOrRemoveTag(@Nullable Node node) {
if (node == null || node.getNodeType() != Node.ELEMENT_NODE) {
return false;
}
NamedNodeMap attrs = node.getAttributes();
Node merge = attrs.getNamedItemNS(TOOLS_URI, MERGE_ATTR);
String value = merge == null ? null : merge.getNodeValue();
return MERGE_OVERRIDE.equals(value) || MERGE_REMOVE.equals(value);
}
@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");
}
@Test
public void testGetNamedItemNS() throws Exception {
Document document = createDOMWithNS("NamedNodeMap03.xml");
NodeList nodeList = document.getElementsByTagName("body");
nodeList = nodeList.item(0).getChildNodes();
Node n = nodeList.item(7);
NamedNodeMap namedNodeMap = n.getAttributes();
Node node = namedNodeMap.getNamedItemNS("urn:BooksAreUs.org:BookInfo", "aaa");
assertEquals(node.getNodeValue(), "value");
}
/**
* 名前空間を指定してNode内の指定した属性値を取得する.
* @param node 対象となる要素(Nodeオブジェクト)
* @param name 取得する属性名
* @param ns 名前空間名
* @return 取得した属性値
*/
private String getAttributeValueNS(final Node node, final String name, final String ns) {
NamedNodeMap nnm = node.getAttributes();
Node attr = nnm.getNamedItemNS(ns, name);
if (attr != null) {
return attr.getNodeValue();
} else {
return "";
}
}
private boolean namedNodeMapsEqual(NamedNodeMap a, NamedNodeMap b) {
if (a.getLength() != b.getLength()) {
return false;
}
for (int i = 0; i < a.getLength(); i++) {
Node aNode = a.item(i);
Node bNode = aNode.getLocalName() == null
? b.getNamedItem(aNode.getNodeName())
: b.getNamedItemNS(aNode.getNamespaceURI(), aNode.getLocalName());
if (bNode == null || !aNode.isEqualNode(bNode)) {
return false;
}
}
return true;
}
/**
* Returns the value of the attribute on node
* @param node
* @param namespace
* @param name of the attribute
* @return value of the attribute or null
* @throws IllegalArgumentException- if node is null
*/
protected String getNodeAttribute(Node node, String namespace,String name) {
if(node == null )
throw new IllegalArgumentException("Node is null");
NamedNodeMap nodeMap = node.getAttributes();
if (nodeMap == null) {
return null;
}
Node attribute = nodeMap.getNamedItemNS(namespace, name);
if (attribute != null) {
return attribute.getNodeValue();
}
return null;
}
public String jsFunction_getAttributeNS(String namespaceURI, String localName) {
NamedNodeMap attributes = wrappedNode.getAttributes();
Node attrNode = attributes.getNamedItemNS(namespaceURI, localName);
if (attrNode == null) {
return null;
}
Attr attribute = (Attr)attrNode;
return attribute.getValue();
}
@Override
public boolean isNil(XSElementDeclaration elementDeclaration, Node node) {
NamedNodeMap attrs= node.getAttributes();
if (attrs==null) {
return false;
}
Node nilAttribute=attrs.getNamedItemNS(XML_SCHEMA_INSTANCE_NAMESPACE, XML_SCHEMA_NIL_ATTRIBUTE);
return nilAttribute!=null && "true".equals(nilAttribute.getTextContent());
}
private static MergingReport.Result cleanToolsReferences(
Element element,
ILogger logger) {
NamedNodeMap namedNodeMap = element.getAttributes();
if (namedNodeMap != null) {
// make a copy of the original list of attributes as we will remove some during this
// process.
List<Node> attributes = new ArrayList<Node>();
for (int i = 0; i < namedNodeMap.getLength(); i++) {
attributes.add(namedNodeMap.item(i));
}
for (Node attribute : attributes) {
if (SdkConstants.TOOLS_URI.equals(attribute.getNamespaceURI())) {
// we need to special case when the element contained tools:node="remove"
// since it also needs to be deleted unless it had a selector.
// if this is ools:node="removeAll", we always delete the element whether or
// not there is a tools:selector.
boolean hasSelector = namedNodeMap.getNamedItemNS(
SdkConstants.TOOLS_URI, "selector") != null;
if (attribute.getLocalName().equals(NodeOperationType.NODE_LOCAL_NAME)
&& (attribute.getNodeValue().equals(REMOVE_ALL_OPERATION_XML_MAME)
|| (attribute.getNodeValue().equals(REMOVE_OPERATION_XML_MAME))
&& !hasSelector)) {
if (element.getParentNode().getNodeType() == Node.DOCUMENT_NODE) {
logger.error(null /* Throwable */,
String.format(
"tools:node=\"%1$s\" not allowed on top level %2$s element",
attribute.getNodeValue(),
XmlNode.unwrapName(element)));
return ERROR;
} else {
element.getParentNode().removeChild(element);
}
} else {
// anything else, we just clean the attribute.
element.removeAttributeNS(
attribute.getNamespaceURI(), attribute.getLocalName());
}
}
// this could also be the xmlns:tools declaration.
if (attribute.getNodeName().startsWith(SdkConstants.XMLNS_PREFIX)
&& SdkConstants.TOOLS_URI.equals(attribute.getNodeValue())) {
element.removeAttribute(attribute.getNodeName());
}
}
}
// make a copy of the element children since we will be removing some during
// this process, we don't want side effects.
NodeList childNodes = element.getChildNodes();
ImmutableList.Builder<Element> childElements = ImmutableList.builder();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
childElements.add((Element) node);
}
}
for (Element childElement : childElements.build()) {
if (cleanToolsReferences(childElement, logger) == ERROR) {
return ERROR;
}
}
return MergingReport.Result.SUCCESS;
}
/**
* @semantics Navigates through read-only Node tree to determine context and provide right results.
* @postconditions Let ctx unchanged
* @time Performs fast up to 300 ms.
* @stereotype query
* @param virtualElementCtx represents virtual element Node that has to be replaced, its own attributes does not name sense, it can be used just as the navigation start point.
* @return enumeration of <code>GrammarResult</code>s (ELEMENT_NODEs) that can be queried on name, and attributes.
* Every list member represents one possibility.
*/
@Override
public Enumeration<GrammarResult> queryElements(HintContext virtualElementCtx) {
String start = virtualElementCtx.getCurrentPrefix();
Node parentNode = virtualElementCtx.getParentNode();
boolean hasSchema = false;
if (parentNode != null && schemaDoc != null) {
List<String> parentNames = new ArrayList<String>();
while (parentNode != null & parentNode.getNodeName() != null) {
parentNames.add(0, parentNode.getNodeName());
if (parentNode.getParentNode() == null || parentNode.getParentNode().getNodeName() == null) {
NamedNodeMap nnm = parentNode.getAttributes();
hasSchema = nnm.getNamedItemNS("xsi","schemaLocation") != null;
}
parentNode = parentNode.getParentNode();
}
org.jdom.Element schemaParent = schemaDoc.getRootElement();
Iterator<String> it = parentNames.iterator();
String path = ""; //NOI18N
Vector<GrammarResult> toReturn = new Vector<GrammarResult>();
while (it.hasNext() && schemaParent != null) {
String str = it.next();
path = path + "/" + str; //NOI18N
org.jdom.Element el = findElement(schemaParent, str);
if (!it.hasNext()) {
toReturn.addAll(getDynamicCompletion(path, virtualElementCtx, el));
}
if (el != null) {
String type = el.getAttributeValue("type"); //NOI18N
if (type != null) {
schemaParent = findTypeContent(type, schemaDoc.getRootElement());
if (schemaParent == null) {
System.err.println("no schema parent for " + str + " of type " + el.getAttributeValue("type")); //NOI18N
}
} else {
schemaParent = findNonTypedContent(el);
}
} else {
// System.err.println("cannot find element=" + str); //NOI18N
}
}
if (schemaParent != null && !hasSchema) {
processSequence(start, schemaParent, toReturn);
}
return toReturn.elements();
} else {
return Enumerations.<GrammarResult>empty();
}
}
private static MergingReport.Result cleanToolsReferences(
Element element,
ILogger logger) {
NamedNodeMap namedNodeMap = element.getAttributes();
if (namedNodeMap != null) {
// make a copy of the original list of attributes as we will remove some during this
// process.
List<Node> attributes = new ArrayList<Node>();
for (int i = 0; i < namedNodeMap.getLength(); i++) {
attributes.add(namedNodeMap.item(i));
}
for (Node attribute : attributes) {
if (SdkConstants.TOOLS_URI.equals(attribute.getNamespaceURI())) {
// we need to special case when the element contained tools:node="remove"
// since it also needs to be deleted unless it had a selector.
// if this is ools:node="removeAll", we always delete the element whether or
// not there is a tools:selector.
boolean hasSelector = namedNodeMap.getNamedItemNS(
SdkConstants.TOOLS_URI, "selector") != null;
if (attribute.getLocalName().equals(NodeOperationType.NODE_LOCAL_NAME)
&& (attribute.getNodeValue().equals(REMOVE_ALL_OPERATION_XML_MAME)
|| (attribute.getNodeValue().equals(REMOVE_OPERATION_XML_MAME))
&& !hasSelector)) {
if (element.getParentNode().getNodeType() == Node.DOCUMENT_NODE) {
logger.error(null /* Throwable */,
String.format(
"tools:node=\"%1$s\" not allowed on top level %2$s element",
attribute.getNodeValue(),
XmlNode.unwrapName(element)));
return ERROR;
} else {
element.getParentNode().removeChild(element);
}
} else {
// anything else, we just clean the attribute.
element.removeAttributeNS(
attribute.getNamespaceURI(), attribute.getLocalName());
}
}
// this could also be the xmlns:tools declaration.
if (attribute.getNodeName().startsWith(SdkConstants.XMLNS_PREFIX)
&& SdkConstants.TOOLS_URI.equals(attribute.getNodeValue())) {
element.removeAttribute(attribute.getNodeName());
}
}
}
// make a copy of the element children since we will be removing some during
// this process, we don't want side effects.
NodeList childNodes = element.getChildNodes();
ImmutableList.Builder<Element> childElements = ImmutableList.builder();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
childElements.add((Element) node);
}
}
for (Element childElement : childElements.build()) {
if (cleanToolsReferences(childElement, logger) == ERROR) {
return ERROR;
}
}
return MergingReport.Result.SUCCESS;
}
/**
* Compares the attributes of the given nodes.
* Subclasses can override this method if they need a different comparison.
*
* <p><strong>NOTE:</strong> Current implementation requires the number of attributes to be the
* same only if the {@link #ignoredAttributes} set is empty. If the {@code ignoredAttributes}
* set is not empty, then the actual node could have more attributes than the expected node;
* the extra attributes are ignored. This may change in a future version if it appears to be
* a problem in practice.</p>
*
* @param expected the node having the expected attributes.
* @param actual the node to compare.
*/
@SuppressWarnings("null")
protected void compareAttributes(final Node expected, final Node actual) {
final NamedNodeMap expectedAttributes = expected.getAttributes();
final NamedNodeMap actualAttributes = actual.getAttributes();
final int n = (expectedAttributes != null) ? expectedAttributes.getLength() : 0;
if (ignoredAttributes.isEmpty()) {
assertPropertyEquals("nbAttributes", n,
(actualAttributes != null) ? actualAttributes.getLength() : 0, expected, actual);
}
for (int i=0; i<n; i++) {
final Node expAttr = expectedAttributes.item(i);
final String ns = expAttr.getNamespaceURI();
String name = expAttr.getLocalName();
if (name == null) {
/*
* The above variables may be null if the node has been built from a DOM Level 1 API,
* or if the DocumentBuilder was not namespace-aware. In the following table, the first
* column shows the usual case for "http://www.w3.org/2000/xmlns/gml". The second column
* shows the case if the DocumentBuilder was not aware of namespaces. The last column is
* a case sometime observed.
*
* ┌───────────────────┬─────────────────────────────────┬──────────────┬─────────────┐
* │ Node method │ Namespace (NS) aware │ Non NS-aware │ Other case │
* ├───────────────────┼─────────────────────────────────┼──────────────┼─────────────┤
* │ getNamespaceURI() │ "http://www.w3.org/2000/xmlns/" │ null │ "xmlns" │
* │ getLocalName() │ "gml" │ null │ "gml" │
* │ getNodeName() │ "xmlns:gml" │ "xmlns:gml" │ │
* └───────────────────┴─────────────────────────────────┴──────────────┴─────────────┘
*
* By default, this block is not be executed. However if the user gave us Nodes that are
* not namespace aware, then the 'isIgnored(…)' method will try to parse the node name.
*/
name = expAttr.getNodeName();
}
if (!isIgnored(ignoredAttributes, ns, name)) {
final Node actAttr;
if (ns == null) {
actAttr = actualAttributes.getNamedItem(name);
} else {
actAttr = actualAttributes.getNamedItemNS(ns, name);
}
compareNode(expAttr, actAttr);
}
}
}
@NonNull
private static MergingReport.Result cleanToolsReferences(
@NonNull ManifestMerger2.MergeType mergeType,
@NonNull Element element,
@NonNull ILogger logger) {
NamedNodeMap namedNodeMap = element.getAttributes();
if (namedNodeMap != null) {
// make a copy of the original list of attributes as we will remove some during this
// process.
List<Node> attributes = new ArrayList<Node>();
for (int i = 0; i < namedNodeMap.getLength(); i++) {
attributes.add(namedNodeMap.item(i));
}
for (Node attribute : attributes) {
if (SdkConstants.TOOLS_URI.equals(attribute.getNamespaceURI())) {
// we need to special case when the element contained tools:node="remove"
// since it also needs to be deleted unless it had a selector.
// if this is tools:node="removeAll", we always delete the element whether or
// not there is a tools:selector.
boolean hasSelector = namedNodeMap.getNamedItemNS(
SdkConstants.TOOLS_URI, "selector") != null;
if (attribute.getLocalName().equals(NodeOperationType.NODE_LOCAL_NAME)
&& (attribute.getNodeValue().equals(REMOVE_ALL_OPERATION_XML_MAME)
|| (attribute.getNodeValue().equals(REMOVE_OPERATION_XML_MAME))
&& !hasSelector)) {
if (element.getParentNode().getNodeType() == Node.DOCUMENT_NODE) {
logger.error(null /* Throwable */,
String.format(
"tools:node=\"%1$s\" not allowed on top level %2$s element",
attribute.getNodeValue(),
XmlNode.unwrapName(element)));
return ERROR;
} else {
element.getParentNode().removeChild(element);
}
} else {
// anything else, we just clean the attribute unless we are merging for
// libraries.
if (mergeType != ManifestMerger2.MergeType.LIBRARY) {
element.removeAttributeNS(
attribute.getNamespaceURI(), attribute.getLocalName());
}
}
}
// this could also be the xmlns:tools declaration.
if (attribute.getNodeName().startsWith(SdkConstants.XMLNS_PREFIX)
&& SdkConstants.TOOLS_URI.equals(attribute.getNodeValue())
&& mergeType != ManifestMerger2.MergeType.LIBRARY) {
element.removeAttribute(attribute.getNodeName());
}
}
}
// make a copy of the element children since we will be removing some during
// this process, we don't want side effects.
NodeList childNodes = element.getChildNodes();
ImmutableList.Builder<Element> childElements = ImmutableList.builder();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
childElements.add((Element) node);
}
}
for (Element childElement : childElements.build()) {
if (cleanToolsReferences(mergeType, childElement, logger) == ERROR) {
return ERROR;
}
}
return MergingReport.Result.SUCCESS;
}