我有这个 xml 代码
我希望能够拥有一个扫描仪或其他一些要求用户输入的对象,然后使用该输入来匹配某个节点并显示该节点以及它下面的其余部分。
例如,我想要一个选项来搜索姓名、地址、电子邮件、电话或群组。如果我选择名称,我希望能够输入名称“tim”,然后使用该输入来查找节点并将其与兄弟节点一起显示,但仅限于该特定联系人。
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<contactInfo>
<contact>
<name>tim</name>
<primary_address>1111 virginia road</primary_address>
<secondary_address>N/A</secondary_address>
<primary_email>asdf@gmail.com</primary_email>
<backup_email1>N/A</backup_email1>
<backup_email2>N/A</backup_email2>
<primary_phone>703-111-1111</primary_phone>
<backup_phone1>N/A</backup_phone1>
<backup_phone2>N/A</backup_phone2>
<group1>family</group1>
<group2>friends</group2>
</contact>
<contact>
<name>john</name>
<primary_address>1111 pike road</primary_address>
<secondary_address>N/A</secondary_address>
<primary_email>john@gmail.com</primary_email>
<backup_email1>N/A</backup_email1>
<backup_email2>N/A</backup_email2>
<primary_phone>222-222-2222</primary_phone>
<backup_phone1>N/A</backup_phone1>
<backup_phone2>N/A</backup_phone2>
<group1>friends</group1>
<group2>N/A</group2>
</contact>
<contact>
<name>Tim Calara</name>
<primary_address>1234 Wallaby Way</primary_address>
<secondary_address>N/A</secondary_address>
<primary_email>tim@gmail.com</primary_email>
<backup_email1>N/A</backup_email1>
<backup_email2>N/A</backup_email2>
<primary_phone>111-123-4567</primary_phone>
<backup_phone1>N/A</backup_phone1>
<backup_phone2>N/A</backup_phone2>
<group1>family</group1>
<group2>friends</group2>
</contact>
</contactInfo>
这是我的代码的搜索部分,如果您需要我的整个代码,请告诉我(整个代码很长)。
public void search() throws SAXException, IOException, ParserConfigurationException, XPathExpressionException
{
System.out.println("\nSearch for Contact");
int choice = searchMenu ( );
switch (choice)
{
case 1:
try
{
File file = new File("/Users/T/Eclipse Workspace/contactInfo/nData.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document xmlDocument = dBuilder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
System.out.println("Please enter Contact name: ");
String input = kbd.nextLine();
String expression = "/contactInfo/contact[name() = "input"]";
System.out.println(expression);
Node node = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);
if(null != node) {
NodeList nodeList = node.getChildNodes();
for (int i = 0;null!=nodeList && i < nodeList.getLength(); i++) {
Node nod = nodeList.item(i);
if(nod.getNodeType() == Node.ELEMENT_NODE)
System.out.println(nodeList.item(i).getNodeName() + " : " + nod.getFirstChild().getNodeValue());
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
break;
//case 2:
//case 3: email ( ); break;
//case 4: phone ( ); break;
//case 5: break;
//case 6: exit (); break;
}
}