【问题标题】:Getting element using attribute使用属性获取元素
【发布时间】:2011-05-23 05:20:17
【问题描述】:

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

例如<tag1 att="recent">Data</tag1>

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

【问题讨论】:

  • “请指导我。”请正确拼写单词。顺便说一句 - 你有问题吗?

标签: java xml


【解决方案1】:

有很多方法可以做到这一点。您可以使用 xPath (example)、DOM Document 或 SAX Parser (example) 来检索属性值和标记元素。

以下是相关问题:


这是您所要求的解决方法。我绝不会建议这种类型的“hack”,而是使用 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:未提供代码注释。它作为练习提供给读者。 :)

【讨论】:

  • 感谢您的回复。我想解析具有属性的元素。你知道怎么做吗..???我正在使用 DOM 概念
  • 是的,如果你有org.w3c.dom.Element element,你可以说String attribute = element.getAttribute("att");
  • 再次感谢,~ String attribute = element.getAttribute("att");~ 从这里我只能得到属性(即)我在属性中给出的任何东西,我可以通过 String 得到它,但我想借助属性解析元素。
  • @HariRam,为此,您需要使用 SAX Parser。 DOM 解析器生成一个 DOM 文档,因此获取元素和/或属性需要您分别知道元素和/或属性的名称。 SAX 没有。它是一个迭代解析器,您可以实现它应该如何翻译。
  • 好的,但我不知道 Sax 解析器。你能指导我解决这个问题吗?
【解决方案2】:

这是获取具有给定属性名称和值的子节点的 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;
}

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多