使用属性获取元素

我正在使用Java解析Xml,我想借助属性值解析元素。

例如Data

在此我想使用att值解析tag1数据。 我是java和xml的新手。 请指导我。

有办法做到这一点。 您可以使用xPath( 示例 ),DOM Document或SAX Parser( 示例 )来检索属性值和标记元素。

以下是相关问题:

  • 在Java中使用XML元素中的值
  • 如何使用Java检索XML的元素值?

这是您要求的解决方法。 我永远不会建议使用这种类型的“黑客”,而是使用SAX(参见示例链接)。

 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:未提供代码注释。 它是作为练习给予读者的。 🙂

这是获取具有给定属性名称和值的子节点的java代码。 这是你想要的

  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; } 

这是一个老问题,但您可以使用HTMLUnit

  HtmlAnchor a = (HtmlAnchor)ele; url = a.getHrefAttribute();