简体   繁体   English

如何使用 Java 在 XML 文件中搜索关键字?

[英]How do I search for a keyword in a XML file using Java?

I would like to use Java to search an XML file for the word "Smith" and print in the console "Smith, Mike"我想使用 Java 在 XML 文件中搜索单词“Smith”并在控制台中打印“Smith, Mike”

<?xml version = "1.0"?>
<class>
   <student rollno = "1">
      <firstname>Doe</firstname>
      <lastname>Jane</lastname>
   </student>
   
   <student rollno = "2">
      <firstname>Smith</firstname>
      <lastname>Mike</lastname>
   </student>
   
   <student rollno = "3">
      <firstname>Fonda</firstname>
      <lastname>Jane</lastname>
   </student>
</class>

I've found resources online to query the whole XML file but had difficulty finding ways to search inside the tags.我在网上找到了查询整个 XML 文件的资源,但很难找到在标签内搜索的方法。

try with following solution.尝试以下解决方案。 in this example used the DOM Parser for parse XML file.在此示例中,使用 DOM 解析器解析 XML 文件。

String firstName = "";
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first name: ");
firstName = scanner.nextLine();
        
try {
    File inputFile = new File("input.xml");
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(inputFile);
    document.getDocumentElement().normalize();
    NodeList nodeList = document.getElementsByTagName("student");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Element element = (Element) nodeList.item(i);
        if(element.getElementsByTagName("firstname").item(0).getTextContent().equals(firstName)){
            System.out.println("Full Name : "+element.getElementsByTagName("firstname").item(0).getTextContent()+" "+
                                                    element.getElementsByTagName("lastname").item(0).getTextContent());
            break;
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}

console output,控制台 output,

Enter the first name: Smith
Full Name : Smith Mike // when enter the first name as "Smith"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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