Reputation: 863
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
Upvotes: 0
Views: 1319
Reputation: 8552
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();
Upvotes: 1