我是 jaxp 的新手,我被困住了,我必须使用 sax 或 dom 解析这个 xml。我必须要求用户输入员工代码,然后为 ex显示该特定员工的其他节点 :如果用户输入 101,那么我将显示
Ename:akshay
ecode:101
dp no.:10
mgr code=201
我尝试了很多但没有结果,有人可以帮忙。
<employees>
<employee>
<Ename>akshay</Ename>
<Ecode>101</Ecode>
<EmpSal>2100.0</EmpSal>
<Department_code>10</Department_code>
<Manager_code>201</Manager_code>
</employee>
<employee>
<Ename>rahul</Ename>
<Ecode>102</Ecode>
<EmpSal>21000.0</EmpSal>
<Department_code>20</Department_code>
<Manager_code>202</Manager_code>
</employee>
</employees>
我试图解析这个 xml 的代码
public class ParseUsingDom {
public static void main(String[] args) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("emp.xml");
NodeList list = document.getElementsByTagName("*");
int count = 0;
{
for (int i = 0; i < list.getLength(); i++) {
Element element = (Element) list.item(i);
String nodeName = element.getNodeName();
if (nodeName.equals("employee")) {
count++;
System.out.println("Employee :" + count);
} else if (nodeName.equals("Ename")) {
System.out.println("\tEname:\t"
+ element.getChildNodes().item(0).getNodeValue());
} else if (nodeName.equals("Ecode")) {
System.out.println("\tECode:\t"
+ element.getChildNodes().item(0).getNodeValue());
} else if (nodeName.equals("EmpSal")) {
System.out.println("\tEmpsal:\t"
+ element.getChildNodes().item(0).getNodeValue());
} else if (nodeName.equals("Department_code")) {
System.out.println("\tDepartment_code: "
+ element.getChildNodes().item(0).getNodeValue());
} else if (nodeName.equals("Manager_code")) {
System.out.println("\tManager code:\t"
+ element.getChildNodes().item(0).getNodeValue());
}
}
}} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}