简体   繁体   中英

How to get attribute value from xml in android/Java

I have xml in this format

  String xml = "<contact xmlns='com:your:ext:namespace'><phonenumber1>12345675</phonenumber1>           <phonenumber2>56738903</phonenumber2></contact>";

   Document doc = null;
            try {
                InputStream in = new ByteArrayInputStream(xml.getBytes("utf-8"));
                doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            } catch (SAXException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            } catch (ParserConfigurationException e1) {
                e1.printStackTrace();
            }

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e1) {
            e1.printStackTrace();
        }
        doc.getDocumentElement().normalize();
        System.out.println("Root element " + doc.getDocumentElement().getNodeName());

        NodeList nodeList = doc.getElementsByTagName("*");
        for (int i = 0; i < nodeList.getLength(); i++) {
        // Get element
        Element element = (Element) nodeList.item(i);
        //System.out.println(element.getNodeName());

        Node nNode = nodeList.item(i);

        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

            Element eElement = (Element) nNode;

            System.out.println("attribute tags: " + eElement.getTagName());
        }

}

i am using above code to get attaribute values. getting attribute names but fails in getting attribute values please help me i am struct here

thanks in advance

NareshRavva

In your xml none of the elements have attribute "Name" so it cannot return you one.

Judging by the end of your code, you probably want to use getTagName() method, to get element name instead ( phonenumber1 ) is the tag name not its attibute.

Your

NodeList nodeList = doc.getElementsByTagName("*");

already contains the elements of phonenumber1, ... you can recognize them as phone tags by for example:

Element elm = (Elemetn) nNode;
if (elm.getTagName().startsWith("phone"))
   phone = elm.getTextContent();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM