I am parsing Xml using Java, i want to parse element with the help of attribute value.
For example
There are ways to do this. You can use either, xPath (example), DOM Document or SAX Parser (example) to retrieve attribute value and tag elements.
Here's related questions:
This is a workaround to what you requested. I would never suggest that type of "hack", instead, use SAX instead (see example link).
public static Element getElementByAttributeValue(Node rootElement, String attributeValue) {
if (rootElement != null && rootElement.hasChildNodes()) {
NodeList nodeList = rootElement.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node subNode = nodeList.item(i);
if (subNode.hasAttributes()) {
NamedNodeMap nnm = subNode.getAttributes();
for (int j = 0; j < nnm.getLength(); j++) {
Node attrNode = nnm.item(j);
if (attrNode.getNodeType == Node.ATTRIBUTE_NODE) {
Attr attribute = (Attr) attrNode;
if (attributeValue.equals(attribute.getValue()) {
return (Element)subNode;
} else {
return getElementByAttributeValue(subNode, attributeValue);
}
}
}
}
}
}
return null;
}
PS: Code comment not provided. It's given as an exercise to the reader. :)
This is java code to get the child node with given attribute name and value. Is this what you are looking for
public static Element getNodeWithAttribute(Node root, String attrName, String attrValue)
{
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n instanceof Element) {
Element el = (Element) n;
if (el.getAttribute(attrName).equals(attrValue)) {
return el;
}else{
el = getNodeWithAttribute(n, attrName, attrValue); //search recursively
if(el != null){
return el;
}
}
}
}
return null;
}
It is a old question but you may use HTMLUnit
HtmlAnchor a = (HtmlAnchor)ele;
url = a.getHrefAttribute();