Java Code Examples for org.w3c.dom.Node.getAttributes()

The following are Jave code examples for showing how to use getAttributes() of the org.w3c.dom.Node class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: L2jBrasil   File: DocumentBase.java   View Source Code Vote up 8 votes
protected void parseTable(Node n)
{
    NamedNodeMap attrs = n.getAttributes();
    String name = attrs.getNamedItem("name").getNodeValue();
    if (name.charAt(0) != '#') throw new IllegalArgumentException("Table name must start with #");
    StringTokenizer data = new StringTokenizer(n.getFirstChild().getNodeValue());
    List<String> array = new ArrayList<>();
    while (data.hasMoreTokens())
        array.add(data.nextToken());
    String[] res = new String[array.size()];
    int i = 0;
    for (String str : array)
    {
        res[i++] = str;
    }
    setTable(name, res);
}
 
Example 2
Project: javaide   File: NodeUtils.java   View Source Code Vote up 6 votes
static boolean compareElementNode(@NonNull Node node1, @NonNull Node node2, boolean strict) {
    if (!node1.getNodeName().equals(node2.getNodeName())) {
        return false;
    }

    NamedNodeMap attr1 = node1.getAttributes();
    NamedNodeMap attr2 = node2.getAttributes();

    if (!compareAttributes(attr1, attr2)) {
        return false;
    }

    if (strict) {
        return compareChildren(node1.getChildNodes(), node2.getChildNodes());
    }

    return compareContent(node1.getChildNodes(), node2.getChildNodes());
}
 
Example 3
Project: openjdk-jdk10   File: MarkerSegment.java   View Source Code Vote up 6 votes
static int getAttributeValue(Node node,
                             NamedNodeMap attrs,
                             String name,
                             int min,
                             int max,
                             boolean required)
    throws IIOInvalidTreeException {
    if (attrs == null) {
        attrs = node.getAttributes();
    }
    String valueString = attrs.getNamedItem(name).getNodeValue();
    int value = -1;
    if (valueString == null) {
        if (required) {
            throw new IIOInvalidTreeException
                (name + " attribute not found", node);
        }
    } else {
          value = Integer.parseInt(valueString);
          if ((value < min) || (value > max)) {
              throw new IIOInvalidTreeException
                  (name + " attribute out of range", node);
          }
    }
    return value;
}
 
Example 4
Project: bdf2   File: JoinNode.java   View Source Code Vote up 6 votes
@Override
public void parseXml(Node node) {
	super.parseXml(node);
	NamedNodeMap map=node.getAttributes();
	Node lockmodeNode=map.getNamedItem("lockmode");
	if(lockmodeNode!=null){
		LockModeType type=null;
		for(LockModeType mode:LockModeType.values()){
			if(mode.toString().equals(lockmodeNode.getNodeValue())){
				type=mode;
			}
		}
		this.lockmode=type;
	}
	Node multiplicityNode=map.getNamedItem("multiplicity");
	if(multiplicityNode!=null){
		this.multiplicity=multiplicityNode.getNodeValue();
	}
}
 
Example 5
Project: javaide   File: ResourceItem.java   View Source Code Vote up 6 votes
private ResourceValue parsePluralsValue(PluralsResourceValue value) {
    NodeList children = mValue.getChildNodes();
    for (int i = 0, n = children.getLength(); i < n; i++) {
        Node child = children.item(i);

        if (child.getNodeType() == Node.ELEMENT_NODE) {
            NamedNodeMap attributes = child.getAttributes();
            String quantity = getAttributeValue(attributes, ATTR_QUANTITY);
            if (quantity != null) {
                String text = getTextNode(child.getChildNodes());
                text = ValueXmlHelper.unescapeResourceString(text, false, true);
                value.addPlural(quantity, text);
            }
        }
    }

    return value;
}
 
Example 6
Project: incubator-netbeans   File: ColorEditorTest.java   View Source Code Vote up 6 votes
public void testGetValue () throws Exception {
    Color c = new Color (16, 16, 16);
    System.out.println("original "+c);
    XMLPropertyEditor propEd = new ColorEditor();
    propEd.setValue(c);
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Node element = propEd.storeToXML(doc);

    NamedNodeMap nodeMap = element.getAttributes();
    for (int i = 0; i < nodeMap.getLength(); i++) {
        System.out.println("attr "+i+", "+nodeMap.item(i));
    }
    
    propEd.readFromXML(element);
    Color restoredColor = (Color)propEd.getValue();
    System.out.println("restoredColor "+restoredColor);
    assertEquals("Restored value has to be the same", c, restoredColor);
    assertTrue("It is Color", restoredColor instanceof Color);
    assertFalse("It is not SuperColor", restoredColor instanceof ColorEditor.SuperColor);
    System.out.println("GENERATE: " + propEd.getJavaInitializationString ());
    assertEquals ("Generate Java source with UI color.", "new java.awt.Color(16, 16, 16)", propEd.getJavaInitializationString ());
}
 
Example 7
Project: L2J-Global   File: InitialShortcutData.java   View Source Code Vote up 5 votes
/**
 * Parses a shortcut.
 * @param d the node
 */
private void parseShortcuts(Node d)
{
	NamedNodeMap attrs = d.getAttributes();
	final Node classIdNode = attrs.getNamedItem("classId");
	final List<Shortcut> list = new ArrayList<>();
	for (Node c = d.getFirstChild(); c != null; c = c.getNextSibling())
	{
		if ("page".equals(c.getNodeName()))
		{
			attrs = c.getAttributes();
			final int pageId = parseInteger(attrs, "pageId");
			for (Node b = c.getFirstChild(); b != null; b = b.getNextSibling())
			{
				if ("slot".equals(b.getNodeName()))
				{
					list.add(createShortcut(pageId, b));
				}
			}
		}
	}
	
	if (classIdNode != null)
	{
		_initialShortcutData.put(ClassId.getClassId(Integer.parseInt(classIdNode.getNodeValue())), list);
	}
	else
	{
		_initialGlobalShortcutList.addAll(list);
	}
}
 
Example 8
Project: Svg2AndroidXml   File: Svg2Vector.java   View Source Code Vote up 5 votes
/**
 * Convert polygon element into a path.
 */
private static void extractPolyItem(SvgTree avg, SvgLeafNode child, Node currentGroupNode) {
    logger.log(Level.FINE, "Rect found" + currentGroupNode.getTextContent());
    if (currentGroupNode.getNodeType() == Node.ELEMENT_NODE) {

        NamedNodeMap a = currentGroupNode.getAttributes();
        int len = a.getLength();

        for (int itemIndex = 0; itemIndex < len; itemIndex++) {
            Node n = a.item(itemIndex);
            String name = n.getNodeName();
            String value = n.getNodeValue();
            if (name.equals(SVG_STYLE)) {
                addStyleToPath(child, value);
            } else if (presentationMap.containsKey(name)) {
                child.fillPresentationAttributes(name, value);
            } else if (name.equals(SVG_POINTS)) {
                PathBuilder builder = new PathBuilder();
                String[] split = value.split("[\\s,]+");
                float baseX = Float.parseFloat(split[0]);
                float baseY = Float.parseFloat(split[1]);
                builder.absoluteMoveTo(baseX, baseY);
                for (int j = 2; j < split.length; j += 2) {
                    float x = Float.parseFloat(split[j]);
                    float y = Float.parseFloat(split[j + 1]);
                    builder.relativeLineTo(x - baseX, y - baseY);
                    baseX = x;
                    baseY = y;
                }
                builder.relativeClose();
                child.setPathData(builder.toString());
            }
        }
    }
}
 
Example 9
Project: incubator-netbeans   File: HibernateRefactoringUtil.java   View Source Code Vote up 5 votes
private static String getAttributeValue(Node node, String attributeName) {
    if (node == null) {
        return null;
    }

    NamedNodeMap attribs = node.getAttributes();
    if (attribs != null && attribs.getNamedItem(attributeName) != null) { // NOI18N
        return attribs.getNamedItem(attributeName).getNodeValue(); // NOI18N
    }

    return null;
}
 
Example 10
Project: alvisnlp   File: XMLReader.java   View Source Code Vote up 5 votes
private static final org.w3c.dom.Element copyNodeAndAttributes(Node node) {
	org.w3c.dom.Element result = document.createElement(node.getNodeName());
	NamedNodeMap attributes = node.getAttributes();
	for (int i = 0; i < attributes.getLength(); ++i) {
		Node a = attributes.item(i);
		String name = a.getNodeName();
		String value = a.getNodeValue();
		result.setAttribute(name, value);
	}
	return result;
}
 
Example 11
Project: MybatisGeneatorUtil   File: MyBatisGeneratorConfigurationParser.java   View Source Code Vote up 5 votes
protected Properties parseAttributes(Node node) {
    Properties attributes = new Properties();
    NamedNodeMap nnm = node.getAttributes();
    for (int i = 0; i < nnm.getLength(); i++) {
        Node attribute = nnm.item(i);
        String value = parsePropertyTokens(attribute.getNodeValue());
        attributes.put(attribute.getNodeName(), value);
    }

    return attributes;
}
 
Example 12
Project: monarch   File: XmlUtils.java   View Source Code Vote up 5 votes
public static String getAttribute(Node node, String name) {
  NamedNodeMap attributes = node.getAttributes();
  if (attributes == null) {
    return null;
  }

  Node attributeNode = node.getAttributes().getNamedItem(name);
  if (attributeNode == null) {
    return null;
  }
  return attributeNode.getTextContent();
}
 
Example 13
Project: L2J-Global   File: ExperienceData.java   View Source Code Vote up 5 votes
@Override
public void parseDocument(Document doc, File f)
{
	final Node table = doc.getFirstChild();
	final NamedNodeMap tableAttr = table.getAttributes();
	
	MAX_LEVEL = (byte) (Byte.parseByte(tableAttr.getNamedItem("maxLevel").getNodeValue()) + 1);
	MAX_PET_LEVEL = (byte) (Byte.parseByte(tableAttr.getNamedItem("maxPetLevel").getNodeValue()) + 1);
	
	if (MAX_LEVEL > Config.PLAYER_MAXIMUM_LEVEL)
	{
		MAX_LEVEL = Config.PLAYER_MAXIMUM_LEVEL;
	}
	if (MAX_PET_LEVEL > MAX_LEVEL)
	{
		MAX_PET_LEVEL = MAX_LEVEL; // Pet level should not exceed owner level.
	}
	
	int maxLevel = 0;
	for (Node n = table.getFirstChild(); n != null; n = n.getNextSibling())
	{
		if ("experience".equals(n.getNodeName()))
		{
			final NamedNodeMap attrs = n.getAttributes();
			maxLevel = parseInteger(attrs, "level");
			if (maxLevel > Config.PLAYER_MAXIMUM_LEVEL)
			{
				break;
			}
			_expTable.put(maxLevel, parseLong(attrs, "tolevel"));
		}
	}
}
 
Example 14
Project: call-IDE   File: BuildSys.java   View Source Code Vote up 5 votes
/**
 * Description: Editing the xml file for compiling files.
 * @param init path to the xml file
 * @param sourceFile path to the source to be compiled
 */
public static void setPropsForCompileFile(String init, String sourceFile) {
    try {
        File file = new File(sourceFile);
        
        String filepath = init;
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(filepath);
        
        // get project 
        //Node project = doc.getFirstChild();
        Node prop1 = doc.getElementsByTagName("property").item(0);
        Node prop2 = doc.getElementsByTagName("property").item(1);
        Node prop3 = doc.getElementsByTagName("property").item(2);
        
        NamedNodeMap srcAttr = prop1.getAttributes();
        Node srcName = srcAttr.getNamedItem("location");
        srcName.setTextContent( file.getParent());
        
        NamedNodeMap buildAttr = prop2.getAttributes();
        Node buildName = buildAttr.getNamedItem("location");
        buildName.setTextContent( file.getParent());
        
        NamedNodeMap fileAttr = prop3.getAttributes();
        Node fileName = fileAttr.getNamedItem("value");
        fileName.setTextContent( file.getName());
        
        updateBuildFile( filepath, doc);
        
    } catch (Exception ex) {}
}
 
Example 15
Project: openjdk-jdk10   File: DHTMarkerSegment.java   View Source Code Vote up 5 votes
Htable(Node node) throws IIOInvalidTreeException {
    if (node.getNodeName().equals("dhtable")) {
        NamedNodeMap attrs = node.getAttributes();
        int count = attrs.getLength();
        if (count != 2) {
            throw new IIOInvalidTreeException
                ("dhtable node must have 2 attributes", node);
        }
        tableClass = getAttributeValue(node, attrs, "class", 0, 1, true);
        tableID = getAttributeValue(node, attrs, "htableId", 0, 3, true);
        if (node instanceof IIOMetadataNode) {
            IIOMetadataNode ourNode = (IIOMetadataNode) node;
            JPEGHuffmanTable table =
                (JPEGHuffmanTable) ourNode.getUserObject();
            if (table == null) {
                throw new IIOInvalidTreeException
                    ("dhtable node must have user object", node);
            }
            numCodes = table.getLengths();
            values = table.getValues();
        } else {
            throw new IIOInvalidTreeException
                ("dhtable node must have user object", node);
        }
    } else {
        throw new IIOInvalidTreeException
            ("Invalid node, expected dqtable", node);
    }

}
 
Example 16
Project: BestConfig   File: TomcatConfigReadin.java   View Source Code Vote up 4 votes
private static void writetoConfigfile(HashMap hm) {
	String iniConf = "data/server-initial.xml", updatedConf="data/server.xml";
	
	try {
		//we first read in the base line
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dbBuilder;
		dbBuilder = dbFactory.newDocumentBuilder();
		Document doc = dbBuilder.parse(new File(iniConf));
		
		//now we find the place to change
		NodeList connList = doc.getElementsByTagName("Connector");
		boolean done = false;
		for (int i = 0; i < connList.getLength() && !done; i++) {
			Node connNode = connList.item(i);
			if (connNode.getNodeType() == Node.ELEMENT_NODE) {
				 NamedNodeMap map = connNode.getAttributes();
				 for(int j=0;j<map.getLength() && !done;j++){
					 if(map.item(j).getNodeName().equals("port") &&
							 map.item(j).getNodeValue().equals("8080")){
						 /** now we update the config file as needed*/
						 Element ele = (Element)connNode;
						 for(Object obj : hm.entrySet()){
							 Map.Entry ent = (Map.Entry)obj;
							 ele.setAttribute(ent.getKey().toString(), ent.getValue().toString());
						 }
						 done=true;
					 }
				 }
			}
		}
		
		//updated! we write the config out to file
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new File(updatedConf));
		transformer.transform(source, result);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 17
Project: incubator-netbeans   File: SpringXMLConfigEditorUtils.java   View Source Code Vote up 4 votes
public static final boolean hasAttribute(Node node, String attributeName) {
    return (node != null && node.getAttributes() != null && node.getAttributes().getNamedItem(attributeName) != null);
}
 
Example 18
Project: openjdk-jdk10   File: CoreDocumentImpl.java   View Source Code Vote up 4 votes
/**
 * Traverses the DOM Tree and expands deferred nodes and their
 * children.
 *
 */
protected void undeferChildren(Node node) {

    Node top = node;

    while (null != node) {

        if (((NodeImpl)node).needsSyncData()) {
            ((NodeImpl)node).synchronizeData();
        }

        NamedNodeMap attributes = node.getAttributes();
        if (attributes != null) {
            int length = attributes.getLength();
            for (int i = 0; i < length; ++i) {
                undeferChildren(attributes.item(i));
            }
        }

        Node nextNode = null;
        nextNode = node.getFirstChild();

        while (null == nextNode) {

            if (top.equals(node))
                break;

            nextNode = node.getNextSibling();

            if (null == nextNode) {
                node = node.getParentNode();

                if ((null == node) || (top.equals(node))) {
                    nextNode = null;
                    break;
                }
            }
        }

        node = nextNode;
    }
}
 
Example 19
Project: openjdk-jdk10   File: JPEGMetadata.java   View Source Code Vote up 4 votes
/**
 * Merge the given DHT node into the marker sequence.  If there already
 * exist DHT marker segments in the sequence, then each table in the
 * node replaces the first table, in any DHT segment, with the same
 * table class and table id.  If none of the existing DHT segments contain
 * a table with the same class and id, then the table is added to the last
 * existing DHT segment.
 * If there are no DHT segments, then a new one is created and added
 * as follows:
 * If there are DQT segments, the new DHT segment is inserted immediately
 * following the last DQT segment.
 * If there are no DQT segments, the new DHT segment is inserted before
 * an SOF segment, if there is one.
 * If there is no SOF segment, the new DHT segment is inserted before
 * the first SOS segment, if there is one.
 * If there is no SOS segment, the new DHT segment is added to the end
 * of the sequence.
 */
private void mergeDHTNode(Node node) throws IIOInvalidTreeException {
    // First collect any existing DQT nodes into a local list
    ArrayList<DHTMarkerSegment> oldDHTs = new ArrayList<>();
    Iterator<MarkerSegment> iter = markerSequence.iterator();
    while (iter.hasNext()) {
        MarkerSegment seg = iter.next();
        if (seg instanceof DHTMarkerSegment) {
            oldDHTs.add((DHTMarkerSegment) seg);
        }
    }
    if (!oldDHTs.isEmpty()) {
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            NamedNodeMap attrs = child.getAttributes();
            int childID = MarkerSegment.getAttributeValue(child,
                                                          attrs,
                                                          "htableId",
                                                          0, 3,
                                                          true);
            int childClass = MarkerSegment.getAttributeValue(child,
                                                             attrs,
                                                             "class",
                                                             0, 1,
                                                             true);
            DHTMarkerSegment dht = null;
            int tableIndex = -1;
            for (int j = 0; j < oldDHTs.size(); j++) {
                DHTMarkerSegment testDHT = oldDHTs.get(j);
                for (int k = 0; k < testDHT.tables.size(); k++) {
                    DHTMarkerSegment.Htable testTable = testDHT.tables.get(k);
                    if ((childID == testTable.tableID) &&
                        (childClass == testTable.tableClass)) {
                        dht = testDHT;
                        tableIndex = k;
                        break;
                    }
                }
                if (dht != null) break;
            }
            if (dht != null) {
                dht.tables.set(tableIndex, dht.getHtableFromNode(child));
            } else {
                dht = oldDHTs.get(oldDHTs.size()-1);
                dht.tables.add(dht.getHtableFromNode(child));
            }
        }
    } else {
        DHTMarkerSegment newGuy = new DHTMarkerSegment(node);
        int lastDQT = findMarkerSegmentPosition(DQTMarkerSegment.class, false);
        int firstSOF = findMarkerSegmentPosition(SOFMarkerSegment.class, true);
        int firstSOS = findMarkerSegmentPosition(SOSMarkerSegment.class, true);
        if (lastDQT != -1) {
            markerSequence.add(lastDQT+1, newGuy);
        } else if (firstSOF != -1) {
            markerSequence.add(firstSOF, newGuy);
        } else if (firstSOS != -1) {
            markerSequence.add(firstSOS, newGuy);
        } else {
            markerSequence.add(newGuy);
        }
    }
}
 
Example 20
Project: defense-solutions-proofs-of-concept   File: CoTAdapterInbound.java   View Source Code Vote up 4 votes
public static String elementToString(Node n) throws Exception {
	try {
		String name = n.getNodeName();
		short type = n.getNodeType();

		if (Node.CDATA_SECTION_NODE == type) {
			return "<![CDATA[" + n.getNodeValue() + "]]&gt;";
		}

		if (name.startsWith("#")) {
			return "";
		}

		StringBuffer sb = new StringBuffer();
		sb.append('<').append(name);

		NamedNodeMap attrs = n.getAttributes();
		if (attrs != null) {
			for (int i = 0; i < attrs.getLength(); i++) {
				Node attr = attrs.item(i);
				sb.append(' ').append(attr.getNodeName()).append("=\"")
						.append(attr.getNodeValue()).append("\"");
			}
		}

		String textContent = null;
		NodeList children = n.getChildNodes();

		if (children.getLength() == 0) {
			if ((textContent = n.getTextContent()) != null
					&& !"".equals(textContent)) {
				sb.append(textContent).append("</").append(name)
						.append('>');
			} else {
				sb.append("/>").append('\n');
			}
		} else {
			sb.append('>').append('\n');
			boolean hasValidChildren = false;
			for (int i = 0; i < children.getLength(); i++) {
				String childToString = elementToString(children.item(i));
				if (!"".equals(childToString)) {
					sb.append(childToString);
					hasValidChildren = true;
				}
			}

			if (!hasValidChildren
					&& ((textContent = n.getTextContent()) != null)) {
				sb.append(textContent);
			}

			sb.append("</").append(name).append('>');
		}

		return sb.toString();
	} catch (Exception e) {
		log.error(e);
		log.error(e.getStackTrace());
		throw (e);
	}
}