使用属性获取元素 [英] Getting element using attribute

查看:101
本文介绍了使用属性获取元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am parsing Xml using Java, i want to parse element with the help of attribute value.

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

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

In this i want to parse tag1 data using att value. I am new to java and xml. pls guide me.

推荐答案

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

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.

以下是相关问题:


  • 用Java抓取XML元素中的值

  • < a href =https://stackoverflow.com/questions/4076910/how-to-retrieve-element-value-of-xml-using-java>如何使用Java检索XML的元素值?

  • Grabbing values in XML elements in Java
  • how to retrieve element value of XML using Java?

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

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

PS: Code comment not provided. It's given as an exercise to the reader. :)

这篇关于使用属性获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆