Topic
No replies
SystemAdmin
SystemAdmin
1830 Posts
ACCEPTED ANSWER

Pinned topic How to get a xml id value in java

‏2013-01-30T20:06:11Z |
i am newble to xml,i'm doing xml keyword search project the user may search any value in the xml code,
if the user search 20000
the result will available in id 1001 and 2001
so the o/p like
ms
dhoni
msd
200000

yuraj
singh
yuvi
20000

so extract all related information

i try to wrote some code but i getting error plz any one correct my code

<company>
<staff id="1001">
<firstname>sachin</firstname>
<lastname>tendulkar</lastname>
<nickname>TON</nickname>
<salary>100000</salary>
</staff>
<staff id="2001">
<firstname>MS</firstname>
<lastname>Dhoni</lastname>
<nickname>MSD</nickname>
<salary>200000</salary>
</staff>

<staff id="3001">
<firstname>yuraj</firstname>
<lastname>singh</lastname>
<nickname>yuvi</nickname>
<salary>200000</salary>
</staff>

</company>

public class TestJava
{

public static void main(String[] args) {
TestJava();
}

private static void TestJava() {

String s="MSD";
try {

File fXmlFile = new File("E:/xml/xml/src/a/test.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

NodeList nList = doc.getElementsByTagName("staff");

System.out.println("----------------------------");

for (int temp = 0; temp < nList.getLength(); temp++) {

Node nNode = nList.item(temp);

System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {

Element eElement = (Element) nNode;
System.out.println("========>"+eElement.getAttribute("id").contains(s));

if(eElement.getElementsByTagName("salary").item(0).getTextContent().equals("200000"))
{
System.out.println("Staff id : " + eElement.getAttribute("id"));
System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

}