下面列出了java.text.AttributedCharacterIterator.Attribute#org.w3c.dom.NamedNodeMap 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void traverse(Node node, int depth) {
indent(depth);
System.out.print("<"+node.getNodeName());
if (node.hasAttributes()) {
NamedNodeMap attrs = node.getAttributes();
for (int i=0; i<attrs.getLength(); i++) {
System.out.print(" "+((Attr)attrs.item(i)).getName()+"=\""+((Attr)attrs.item(i)).getValue()+"\"");
}
}
if (node.hasChildNodes()) {
System.out.println(">");
depth+=4;
for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
traverse(child, depth);
}
depth-=4;
indent(depth);
System.out.println("</"+node.getNodeName()+">");
}
else {
System.out.println("/>");
}
}
/**
* Find subsystems from profile node
*/
private List<String> findSubsystemsInProfile(NodeList nodeList) {
List<String> output = new LinkedList<>();
for (int i = 0; i < nodeList.getLength(); i++) {
Node tempNode = nodeList.item(i);
if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
String nodeName = tempNode.getNodeName();
if (!nodeName.contains("subsystem")) {
continue;
}
if (tempNode.hasAttributes()) {
NamedNodeMap nodeMap = tempNode.getAttributes();
for (int j = 0; j < nodeMap.getLength(); j++) {
Node node = nodeMap.item(j);
if (node.getNodeName().equals("xmlns")) {
output.add(node.getNodeValue());
}
}
}
}
}
return output;
}
/**
* Starts the merge process
*
* @param mainDoc The document to edit.
* @param mergeDoc The document containing the edit instructions.
* @throws XPathException A problem parsing the XPath location.
*/
protected void applyMerge(Document mainDoc, Document mergeDoc) throws XPathException {
NodeList mergeActions = handler.getNodeList(mergeDoc, BASE_XPATH_EXPR);
for (int i = 0; i < mergeActions.getLength(); i++) {
Node node = mergeActions.item(i);
// get the attribute map and action information
NamedNodeMap attrMap = node.getAttributes();
String type = attrMap.getNamedItem(ATTR_TYPE).getNodeValue();
String action = attrMap.getNamedItem(ATTR_ACTION).getNodeValue();
String xpath = attrMap.getNamedItem(ATTR_XPATH).getNodeValue();
NodeList actionArgs = node.getChildNodes();
// perform the transform
performTransform(mainDoc, type, action, xpath, actionArgs);
}
}
private void mergeStandardTextNode(Node node)
throws IIOInvalidTreeException {
// Convert to comments. For the moment ignore the encoding issue.
// Ignore keywords, language, and encoding (for the moment).
// If compression tag is present, use only entries with "none".
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
NamedNodeMap attrs = child.getAttributes();
Node comp = attrs.getNamedItem("compression");
boolean copyIt = true;
if (comp != null) {
String compString = comp.getNodeValue();
if (!compString.equals("none")) {
copyIt = false;
}
}
if (copyIt) {
String value = attrs.getNamedItem("value").getNodeValue();
COMMarkerSegment com = new COMMarkerSegment(value);
insertCOMMarkerSegment(com);
}
}
}
private Option<XmlScope> getScopeAttr(Node node) {
return Option.of(node.getAttributes()).fold(new Option.OptionCB<NamedNodeMap, Option<XmlScope>>() {
@Override
public Option<XmlScope> absent() {
return Option.absent();
}
@Override
public Option<XmlScope> present(NamedNodeMap namedNodeMap) {
for (Node attr : new NamedNodeMapCollection(namedNodeMap)) {
Matcher matcher = attrPattern.matcher(attr.toString());
if(matcher.matches() && scopeAttrNameResolver.getScopeAttrName().equals(matcher.group(1))) {
return Option.of(new XmlScope(matcher.group(2)));
}
}
return Option.absent();
}
});
}
@Override
public Document modifyDocument(Document document, String value) {
if (value == null || value.isEmpty()) {
LOGGER.debug( " value is empty " + this.getClass());
return document;
}
try {
Node parentNode = getNodeFromXpath(document);
NamedNodeMap attr = parentNode.getAttributes();
Node nodeAttr = attr.getNamedItem(DEFAULT_ATTRIBUTE_NAME);
if (StringUtils.isNotEmpty(value)) {
nodeAttr.setTextContent(value);
} else {
parentNode.getParentNode().removeChild(parentNode);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Update " + getAttributeValue() +" attribute of bean "+getIdBeanParent()+ " with value "+ value);
}
} catch (XPathExpressionException ex) {
LOGGER.warn(ex);
}
return document;
}
public static Document replaceSystemPropsInXml(Document doc) {
NodeList nodeList = doc.getElementsByTagName("*");
for (int i = 0, len = nodeList.getLength(); i < len; i++) {
Node node = nodeList.item(i);
if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
if (node.hasAttributes()) {
NamedNodeMap attributes = node.getAttributes();
for (int j = 0; j < attributes.getLength(); j++) {
Node attribute = attributes.item(j);
attribute.setTextContent(XMLUtil.replaceSystemPropsInString(attribute.getTextContent()));
}
}
if (node.hasChildNodes()) {
NodeList children = node.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
String value = children.item(j).getNodeValue();
if (value != null) {
children.item(j).setNodeValue(XMLUtil.replaceSystemPropsInString(value));
}
}
}
}
}
return doc;
}
void updateFromNativeNode(Node node, boolean fromScratch)
throws IIOInvalidTreeException {
// Only the transform is required
NamedNodeMap attrs = node.getAttributes();
transform = getAttributeValue(node, attrs, "transform", 0, 2, true);
int count = attrs.getLength();
if (count > 4) {
throw new IIOInvalidTreeException
("Adobe APP14 node cannot have > 4 attributes", node);
}
if (count > 1) {
int value = getAttributeValue(node, attrs, "version",
100, 255, false);
version = (value != -1) ? value : version;
value = getAttributeValue(node, attrs, "flags0", 0, 65535, false);
flags0 = (value != -1) ? value : flags0;
value = getAttributeValue(node, attrs, "flags1", 0, 65535, false);
flags1 = (value != -1) ? value : flags1;
}
}
private void unmarshalParams(Element paramsElem) {
String xPath = paramsElem.getFirstChild().getNodeValue();
// create a Map of namespace prefixes
NamedNodeMap attributes = paramsElem.getAttributes();
if (attributes != null) {
int length = attributes.getLength();
Map<String, String> namespaceMap =
new HashMap<String, String>(length);
for (int i = 0; i < length; i++) {
Attr attr = (Attr)attributes.item(i);
String prefix = attr.getPrefix();
if (prefix != null && prefix.equals("xmlns")) {
namespaceMap.put(attr.getLocalName(), attr.getValue());
}
}
this.params = new XPathFilterParameterSpec(xPath, namespaceMap);
} else {
this.params = new XPathFilterParameterSpec(xPath);
}
}
private void initModelAdmissibleValues(NodeList nodes, Model model) throws Exception {
int nodesLength = nodes.getLength();
for (int j = 0; j < nodesLength; j++) {
NamedNodeMap nodeAttributes = nodes.item(j).getAttributes();
if (nodeAttributes != null) {
String typeId = nodeAttributes.getNamedItem("typeId").getNodeValue();
ModelPropertyType propertyType = getModelPropertyType(model, typeId);
NodeList values = nodes.item(j).getChildNodes();
for (int z = 0; z < values.getLength(); z++) {
Node n = values.item(z);
String nodeName = n.getNodeName();
if ("value".equalsIgnoreCase(nodeName)) {
/**
* TODO REVIEW FOR PORTING
*/
String value = values.item(z).getTextContent();
propertyType.getAdmissibleValues().add(value);
}
}
}
}
}
/**
* Validates attributes of a <jaxb:bindings> element.
*/
private void validate( Element bindings ) {
NamedNodeMap atts = bindings.getAttributes();
for( int i=0; i<atts.getLength(); i++ ) {
Attr a = (Attr)atts.item(i);
if( a.getNamespaceURI()!=null )
continue; // all foreign namespace OK.
if( a.getLocalName().equals("node") )
continue;
if( a.getLocalName().equals("schemaLocation"))
continue;
if( a.getLocalName().equals("scd") )
continue;
// enhancements
if( a.getLocalName().equals("required") ) //
continue;
if( a.getLocalName().equals("multiple") ) //
continue;
// TODO: flag error for this undefined attribute
}
}
/**
* 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;
}
}
/**
* Copies attributes from one {@link Element} to the other.
* @param source source element
* @param destination destination element
*/
private void copyAttributes(@Nullable Element source, Element destination) {
if (source == null) {
return;
}
NamedNodeMap attributes = source.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Attr attribute = (Attr) attributes.item(i);
Attr destAttribute = destination.getAttributeNodeNS(attribute.getNamespaceURI(), attribute.getName());
if (destAttribute == null) {
destination.setAttributeNodeNS((Attr) document.importNode(attribute, true));
} else {
destAttribute.setValue(attribute.getValue());
}
}
}
protected static String createContext(String source, Node ctx) {
// Create the context to parse the document against
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><dummy");
// Run through each node up to the document node and find any xmlns: nodes
Map<String, String> storedNamespaces = new HashMap<String, String>();
Node wk = ctx;
while (wk != null) {
NamedNodeMap atts = wk.getAttributes();
if (atts != null) {
for (int i = 0; i < atts.getLength(); ++i) {
Node att = atts.item(i);
String nodeName = att.getNodeName();
if ((nodeName.equals("xmlns") || nodeName.startsWith("xmlns:"))
&& !storedNamespaces.containsKey(att.getNodeName())) {
sb.append(" " + nodeName + "=\"" + att.getNodeValue() + "\"");
storedNamespaces.put(nodeName, att.getNodeValue());
}
}
}
wk = wk.getParentNode();
}
sb.append(">" + source + "</dummy>");
return sb.toString();
}
public static void traverse(Node node, int depth) {
indent(depth);
System.out.print("<"+node.getNodeName());
if (node.hasAttributes()) {
NamedNodeMap attrs = node.getAttributes();
for (int i=0; i<attrs.getLength(); i++) {
System.out.print(" "+((Attr)attrs.item(i)).getName()+"=\""+((Attr)attrs.item(i)).getValue()+"\"");
}
}
if (node.hasChildNodes()) {
System.out.println(">");
depth+=4;
for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
traverse(child, depth);
}
depth-=4;
indent(depth);
System.out.println("</"+node.getNodeName()+">");
}
else {
System.out.println("/>");
}
}
private boolean updateWithSampleDataSource(Document domainDoc){
boolean sampleExists = false;
NodeList dataSourceNodeList = domainDoc.getElementsByTagName(CONST_JDBC);
for(int i=0; i<dataSourceNodeList.getLength(); i++){
Node dsNode = dataSourceNodeList.item(i);
NamedNodeMap dsAttrMap = dsNode.getAttributes();
String jndiName = dsAttrMap.getNamedItem(CONST_JNDINAME).getNodeValue();
if(jndiName.equals(SAMPLE_DATASOURCE)) {
sampleExists = true;
}
}
if(!sampleExists) {
return createSampleDatasource(domainDoc);
}
return true;
}
/**
* Initialize namespace support by collecting all of the namespace
* declarations in the root's ancestors. This is necessary to
* support schemas fragments, i.e. schemas embedded in other
* documents. See,
*
* https://jaxp.dev.java.net/issues/show_bug.cgi?id=43
*
* Requires the DOM to be created with namespace support enabled.
*/
private void initNamespaceSupport(Element schemaRoot) {
fNamespaceSupport = new SchemaNamespaceSupport();
fNamespaceSupport.reset();
Node parent = schemaRoot.getParentNode();
while (parent != null && parent.getNodeType() == Node.ELEMENT_NODE
&& !parent.getNodeName().equals("DOCUMENT_NODE"))
{
Element eparent = (Element) parent;
NamedNodeMap map = eparent.getAttributes();
int length = (map != null) ? map.getLength() : 0;
for (int i = 0; i < length; i++) {
Attr attr = (Attr) map.item(i);
String uri = attr.getNamespaceURI();
// Check if attribute is an ns decl -- requires ns support
if (uri != null && uri.equals("http://www.w3.org/2000/xmlns/")) {
String prefix = attr.getLocalName().intern();
if (prefix == "xmlns") prefix = "";
// Declare prefix if not set -- moving upwards
if (fNamespaceSupport.getURI(prefix) == null) {
fNamespaceSupport.declarePrefix(prefix,
attr.getValue().intern());
}
}
}
parent = parent.getParentNode();
}
}
private static String getUniqueNsAttribute(NamedNodeMap attributes) {
if (attributes == null) {
return "xmlns:ns1";
}
int i = 2;
while (true) {
String name = String.format("xmlns:ns%d", i++);
if (attributes.getNamedItem(name) == null) {
return name;
}
}
}
ComponentSpec(Node node) throws IIOInvalidTreeException {
NamedNodeMap attrs = node.getAttributes();
componentId = getAttributeValue(node, attrs, "componentId", 0, 255, true);
HsamplingFactor = getAttributeValue(node, attrs, "HsamplingFactor",
1, 255, true);
VsamplingFactor = getAttributeValue(node, attrs, "VsamplingFactor",
1, 255, true);
QtableSelector = getAttributeValue(node, attrs, "QtableSelector",
0, 3, true);
}
/**
* Given a prefix and a Context Node, get the corresponding namespace.
* Warning: This will not work correctly if namespaceContext
* is an attribute node.
* @param prefix Prefix to resolve.
* @param namespaceContext Node from which to start searching for a
* xmlns attribute that binds a prefix to a namespace.
* @return Namespace that prefix resolves to, or null if prefix
* is not bound.
*/
public String getNamespaceForPrefix(String prefix,
org.w3c.dom.Node namespaceContext) {
Node parent = namespaceContext;
String namespace = null;
if (prefix.equals("xml")) {
namespace = S_XMLNAMESPACEURI;
} else {
int type;
while ((null != parent) && (null == namespace)
&& (((type = parent.getNodeType()) == Node.ELEMENT_NODE)
|| (type == Node.ENTITY_REFERENCE_NODE))) {
if (type == Node.ELEMENT_NODE) {
NamedNodeMap nnm = parent.getAttributes();
for (int i = 0; i < nnm.getLength(); i++) {
Node attr = nnm.item(i);
String aname = attr.getNodeName();
boolean isPrefix = aname.startsWith("xmlns:");
if (isPrefix || aname.equals("xmlns")) {
int index = aname.indexOf(':');
String p =isPrefix ?aname.substring(index + 1) :"";
if (p.equals(prefix)) {
namespace = attr.getNodeValue();
break;
}
}
}
}
parent = parent.getParentNode();
}
}
return namespace;
}
protected String pull(Node n, String name) {
NamedNodeMap map = n.getAttributes();
Node attr = map.getNamedItem(name);
if (attr == null)
return null;
return attr.getNodeValue();
}
private final void writeAttributes(final Element element, final XMLStreamWriter writer) throws Exception
{
NamedNodeMap attrs = element.getAttributes();
if (attrs == null)
return;
for (int idx = 0; idx < attrs.getLength(); ++idx)
{
Node attr = attrs.item(idx);
writer.writeAttribute(attr.getNodeName(), attr.getNodeValue());
}
}
private static void appendProperty(Document doc, Node node, String name, String value, boolean force) {
if(force || (value != null && value.length() > 0)) {
Node newProperty = doc.createElement("property");//NOI18N
Attr nameAttr = doc.createAttribute("name");//NOI18N
nameAttr.setValue(name);
Attr valueAttr = doc.createAttribute("value");//NOI18N
valueAttr.setValue(value);
NamedNodeMap attrs = newProperty.getAttributes();
attrs.setNamedItem(nameAttr);
attrs.setNamedItem(valueAttr);
node.appendChild(newProperty);
}
}
/**
* @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);
}
ComponentSpec(Node node) throws IIOInvalidTreeException {
NamedNodeMap attrs = node.getAttributes();
componentId = getAttributeValue(node, attrs, "componentId", 0, 255, true);
HsamplingFactor = getAttributeValue(node, attrs, "HsamplingFactor",
1, 255, true);
VsamplingFactor = getAttributeValue(node, attrs, "VsamplingFactor",
1, 255, true);
QtableSelector = getAttributeValue(node, attrs, "QtableSelector",
0, 3, true);
}
private static void verifyDOMIntegrity(Node node) {
switch (node.getNodeType()) {
case ELEMENT_NODE:
case ATTRIBUTE_NODE:
// DOM level 1?
if (node.getLocalName() == null) {
System.out.println("WARNING: DOM level 1 node found");
System.out.println(" -> node.getNodeName() = " + node.getNodeName());
System.out.println(" -> node.getNamespaceURI() = " + node.getNamespaceURI());
System.out.println(" -> node.getLocalName() = " + node.getLocalName());
System.out.println(" -> node.getPrefix() = " + node.getPrefix());
}
if (node.getNodeType() == ATTRIBUTE_NODE) return;
NamedNodeMap attrs = node.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
verifyDOMIntegrity(attrs.item(i));
}
case DOCUMENT_NODE:
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
verifyDOMIntegrity(children.item(i));
}
}
}
public static Optional<String> getAttributeValue(Node node, String attributeName) {
String retValue = null;
NamedNodeMap attributeMap = node.getAttributes();
for (int k = 0; k < attributeMap.getLength(); k++) {
Node attribute = attributeMap.item(k);
if (attributeName.equals(attribute.getLocalName())) {
retValue = attribute.getNodeValue();
break;
}
}
return retValue == null ? Optional.empty() : Optional.of(retValue);
}
private String getSourceText(Node diskNode) {
NodeList diskChildNodes = diskNode.getChildNodes();
for (int i = 0; i < diskChildNodes.getLength(); i++) {
Node diskChildNode = diskChildNodes.item(i);
if ("source".equals(diskChildNode.getNodeName())) {
NamedNodeMap diskNodeAttributes = diskChildNode.getAttributes();
Node diskNodeAttribute = diskNodeAttributes.getNamedItem("file");
if (diskNodeAttribute != null) {
return diskNodeAttribute.getTextContent();
}
diskNodeAttribute = diskNodeAttributes.getNamedItem("dev");
if (diskNodeAttribute != null) {
return diskNodeAttribute.getTextContent();
}
diskNodeAttribute = diskNodeAttributes.getNamedItem("protocol");
if (diskNodeAttribute != null) {
String textContent = diskNodeAttribute.getTextContent();
if ("rbd".equalsIgnoreCase(textContent)) {
diskNodeAttribute = diskNodeAttributes.getNamedItem("name");
if (diskNodeAttribute != null) {
return diskNodeAttribute.getTextContent();
}
}
}
}
}
return null;
}
/**
* Loads the copy fields
*/
protected synchronized void loadCopyFields(Document document, XPath xpath) throws XPathExpressionException {
String expression = "//" + COPY_FIELD;
NodeList nodes = (NodeList)xpath.evaluate(expression, document, XPathConstants.NODESET);
for (int i=0; i<nodes.getLength(); i++) {
Node node = nodes.item(i);
NamedNodeMap attrs = node.getAttributes();
String source = DOMUtil.getAttr(attrs, SOURCE, COPY_FIELD + " definition");
String dest = DOMUtil.getAttr(attrs, DESTINATION, COPY_FIELD + " definition");
String maxChars = DOMUtil.getAttr(attrs, MAX_CHARS);
int maxCharsInt = CopyField.UNLIMITED;
if (maxChars != null) {
try {
maxCharsInt = Integer.parseInt(maxChars);
} catch (NumberFormatException e) {
log.warn("Couldn't parse {} attribute for '{}' from '{}' to '{}' as integer. The whole field will be copied."
, MAX_CHARS, COPY_FIELD, source, dest);
}
}
if (dest.equals(uniqueKeyFieldName)) {
String msg = UNIQUE_KEY + " field ("+uniqueKeyFieldName+
") can not be the " + DESTINATION + " of a " + COPY_FIELD + "(" + SOURCE + "=" +source+")";
log.error(msg);
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
registerCopyField(source, dest, maxCharsInt);
}
for (Map.Entry<SchemaField, Integer> entry : copyFieldTargetCounts.entrySet()) {
if (entry.getValue() > 1 && !entry.getKey().multiValued()) {
log.warn("Field {} is not multivalued and destination for multiople {} ({})"
, entry.getKey().name, COPY_FIELDS, entry.getValue());
}
}
}
private static Map getOrigin(Element element)
{
String mode = "";
String namc = "";
Properties info = new Properties();
NamedNodeMap atts = element.getAttributes();
for (int i = 0; i < atts.getLength(); i ++)
{
Node attr = atts.item(i);
String name = attr.getNodeName();
String value = attr.getNodeValue();
if ("jndi".equals(name))
{
mode = value;
}
if ("name".equals(name))
{
namc = value;
}
else
{
info.setProperty(name, value);
}
}
// 2016/9/4 增加 source,origin 的 param 节点, 附加设置可使用 param
getProperties(element, info);
Map origin = new HashMap();
origin.put("jndi", mode);
origin.put("name", namc);
origin.put("info", info);
return origin;
}