解析XML文件并在Java中打印出相应的NodeList

时间:2013-01-21 04:40:02

标签: java xml parsing dom

我有一个XML文件,我想根据Java中的控制台输入进行搜索。如果输入在某个标记内找到匹配项,则应打印出相应的NodeList。我搜索过但无法找到我要找的东西。

XML文件:

<DATABASE>
    <USER>
        <ID>1</ID>
        <FIRSTNAME>User</FIRSTNAME>
        <LASTNAME>Name</LASTNAME>
        <USERNAME>username</USERNAME>
        <PASSWORD>password</PASSWORD>
    </USER>
     <USER>
        <ID>2</ID>
        <FIRSTNAME>John</FIRSTNAME>
        <LASTNAME>Doe</LASTNAME>
        <USERNAME>john.doe</USERNAME>
        <PASSWORD>password</PASSWORD>
    </USER>
</DATABASE>

爪哇:

private void viewByUsername() throws ParserConfigurationException, IOException,
    SAXException, TransformerConfigurationException{
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter username to find: ");
    String input = scan.nextLine();

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse("XMLData/UserDatabase.xml");

    doc.getDocumentElement().normalize();

    NodeList users = doc.getElementsByTagName("USER");

    for (int temp = 0; temp < users.getLength(); temp++){
        Node nNode = users.item(temp);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) nNode;

        }
    }

0 个答案:

没有答案