如何使用java中的扫描器在xml中搜索特定元素
大家好,我是XML新手,我的教授从未教过我XML,但我有一个作业,我必须使用java创建一个通讯簿,并将其保存/更新为XML文件 这是到目前为止我的代码如何使用java中的扫描器在xml中搜索特定元素,java,xml,Java,Xml,大家好,我是XML新手,我的教授从未教过我XML,但我有一个作业,我必须使用java创建一个通讯簿,并将其保存/更新为XML文件 这是到目前为止我的代码 import java.io.*; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.parsers.*; import javax.xml.tra
import java.io.*;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.util.*;
public class Contact
{
contactInfo contact = new contactInfo();
Scanner kbd = new Scanner (System.in);
public Contact()
{
try
{
String filepath = "c:\\Users\\T\\Eclipse Workspace\\ContactInfo\\nData.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
private int menu()
{
String instring = "";
do
{
System.out.println ("\n\n***welcome to the Contact Directory: \n\n" +
"menu.......\n" +
"1: Add Contact\n" +
"2: Delete Contact\n" +
"3: Update Contact\n" +
"4: Search for Cotnact\n\n" +
"enter your choice: ");
instring = kbd.nextLine ( );
if ((!instring.equals ("1")) && (!instring.equals ("2")) && (!instring.equals ("3"))
&& (!instring.equals ("4")))
System.out.println ("illegal input");
else
break;
} while (true);
return Integer.parseInt (instring);
}
public void arrival ( ) throws ParserConfigurationException, SAXException, IOException, TransformerException, XPathExpressionException
{
int choice = menu ( );
switch (choice)
{
case 1: add ( ); break;
case 2: delete ( ); break;
case 3: update ( ); break;
case 4: search ( ); break;
}
}
public void add() throws ParserConfigurationException, SAXException, IOException, TransformerException
{
System.out.println("\nAdding New Contact");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse("nData.xml");
Element root = document.getDocumentElement();
// Root Element
Element rootElement = document.getDocumentElement();
Collection<Server> svr = new ArrayList<Server>();
svr.add(new Server());
for (Server i : svr)
{
// server elements
Element server = document.createElement("contact");
rootElement.appendChild(server);
Element name = document.createElement("name");
name.appendChild(document.createTextNode(i.getName()));
server.appendChild(name);
Element address1 = document.createElement("primary_address");
address1.appendChild(document.createTextNode(i.getAddress1()));
server.appendChild(address1);
Element address2 = document.createElement("secondary_address");
address2.appendChild(document.createTextNode(i.getAddress2()));
server.appendChild(address2);
Element phone1 = document.createElement("primary_phone");
phone1.appendChild(document.createTextNode(i.getPhone1()));
server.appendChild(phone1);
Element phone2 = document.createElement("backup_phone1");
phone1.appendChild(document.createTextNode(i.getPhone2()));
server.appendChild(phone2);
Element phone3 = document.createElement("backup_phone2");
phone3.appendChild(document.createTextNode(i.getPhone3()));
server.appendChild(phone3);
Element group1 = document.createElement("group1");
group1.appendChild(document.createTextNode(i.getGroup1()));
server.appendChild(group1);
Element group2 = document.createElement("group2");
group2.appendChild(document.createTextNode(i.getGroup2()));
server.appendChild(group2);
root.appendChild(server);
}
DOMSource source = new DOMSource(document);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StreamResult result = new StreamResult("nData.xml");
transformer.transform(source, result);
System.out.println("Done");
}
public class Server
{
public String getName()
{
System.out.println("Please Enter name");
String name = kbd.nextLine();
return name;
}
public String getAddress1()
{
System.out.println("Please enter Primary Address: ");
String address1 = kbd.nextLine();
return address1;
}
public String getAddress2()
{
System.out.println("Please enter Secondary Address (if none, press ENTER): ");
String address2 = kbd.nextLine();
return address2;
}
public String getPhone1()
{
System.out.println("Please enter Primary Phone Number: ");
String phone1 = kbd.nextLine();
return phone1;
}
public String getPhone2()
{
System.out.println("Please enter First Backup Phone Number (if none, press ENTER): ");
String phone2 = kbd.nextLine();
return phone2;
}
public String getPhone3()
{
System.out.println("Please enter Second Backup Phone Number (if none, press ENTER: ");
String phone3 = kbd.nextLine();
return phone3;
}
public String getGroup1()
{
System.out.println("Please enter Group (if none, press ENTER: ");
String group1 = kbd.nextLine();
return group1;
}
public String getGroup2()
{
System.out.println("Please enter Group (if none, Press ENTER: ");
String group2 = kbd.nextLine();
return group2;
}
}
public void delete()
{
System.out.println("\nDeleting Contact");
}
public void update()
{
System.out.println("\nUpdating Contact");
}
public void search() throws SAXException, IOException, ParserConfigurationException, XPathExpressionException
{
System.out.println("\nSearch for Contact");
int choice = searchMenu ( );
switch (choice)
{
case 1:
try
{
File fXmlFile = new File("/Users/T/Eclipse Workspace/contactInfo/nData.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Contact Information");
NodeList nList = doc.getElementsByTagName("contact");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
System.out.println("Please enter Name of Contact: ");
String input = kbd.nextLine();
if (nNode.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) nNode;
if (input == eElement.getElementsByTagName("name").item(0).getTextContent())
{
System.out.println("Name : " + eElement.getElementsByTagName("name").item(0).getTextContent());
System.out.println("Primary Address : " + eElement.getElementsByTagName("primary_address").item(0).getTextContent());
System.out.println("Secondary Address : " + eElement.getElementsByTagName("secondary_address").item(0).getTextContent());
System.out.println("Primary Phone : " + eElement.getElementsByTagName("primary_phone").item(0).getTextContent());
System.out.println("Backup Phone1 : " + eElement.getElementsByTagName("backup_phone1").item(0).getTextContent());
System.out.println("Backup Phone2 : " + eElement.getElementsByTagName("backup_phone2").item(0).getTextContent());
System.out.println("Group : " + eElement.getElementsByTagName("group1").item(0).getTextContent());
System.out.println("Group : " + eElement.getElementsByTagName("group2").item(0).getTextContent());
break;
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
break;
//case 2: address ( ); break;
//case 3: email ( ); break;
//case 4: phone ( ); break;
//case 5: break;
//case 6: exit (); break;
}
}
private int searchMenu ( )
{
String instring = "";
do
{
System.out.print ("search by: \n\n" +
"1: Name(first and last)\n" +
"2: Address\n" +
"3: E-mail\n" +
"4: Phone Number\n" +
"5: Group\n" +
"6: Exit\n\n" +
"Enter your choice: ");
instring = kbd.nextLine ( );
if ((!instring.equals ("1")) && (!instring.equals ("2")) && (!instring.equals ("3"))
&& (!instring.equals ("4")) && (!instring.equals ("5"))&&(!instring.equals("6")))
System.out.println ("illegal input");
else
break;
} while (true);
return Integer.parseInt (instring);
}
我的主课
import java.util.Random;
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import java.util.Scanner;
public class MainClass
{
public static void main (String [ ] args)
{
Contact myContact = new Contact();
Random gen = new Random ( );
try
{
File fXmlFile = new File("/Users/T/Eclipse Workspace/contactInfo/nData.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("contact");
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("Name : " + eElement.getElementsByTagName("name").item(0).getTextContent());
System.out.println("Address : " + eElement.getElementsByTagName("address").item(0).getTextContent());
System.out.println("Phone : " + eElement.getElementsByTagName("phone").item(0).getTextContent());
System.out.println("Group : " + eElement.getElementsByTagName("group").item(0).getTextContent());
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
String filepath = "c:\\Users\\T\\Eclipse Workspace\\ContactInfo\\nData.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
int what = 0;
do
{
what = gen.nextInt (20);
if (what % 1 == 0)
myContact.arrival ( );
else if (what == 17)
break;
} while (true);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
System.out.println("Done");
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
import java.util.Random;
导入java.io.*;
导入javax.xml.parsers.*;
导入javax.xml.transform.*;
导入javax.xml.transform.dom.*;
导入javax.xml.transform.stream.*;
导入org.w3c.dom.*;
导入org.xml.sax.*;
导入java.util.Scanner;
公共类主类
{
公共静态void main(字符串[]args)
{
Contact myContact=新联系人();
Random gen=新的Random();
尝试
{
File fXmlFile=新文件(“/Users/T/eclipseworkspace/contactInfo/nda.xml”);
DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder=dbFactory.newDocumentBuilder();
documentdoc=dBuilder.parse(fXmlFile);
//可选,但推荐
//请阅读以下内容-http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
System.out.println(“根元素:+doc.getDocumentElement().getNodeName());
NodeList nList=doc.getElementsByTagName(“联系人”);
System.out.println(“-------------------------------”;
对于(int-temp=0;temp
我的XML文件如下所示
<?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_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_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>
</contactInfo>
提姆
弗吉尼亚路1111号
不适用
703-111-1111
不适用
不适用
家庭
朋友
厕所
派克道1111号
不适用
222-222-2222
不适用
不适用
朋友
不适用
我希望能够使用扫描仪搜索名称,比如tim,然后使用该名称,显示与该名称相关的所有信息。例如,如果在扫描仪中输入john,则会显示john的地址、电话和通话组
反之亦然,包括地址、组和电话
最近更新了我的代码和xml文件您可以使用
XPath
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file); // uri to your file
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/contactInfo/contact/name[text()='john']");
NodeList nodeList = (NodeList)(expr.evaluate(doc, XPathConstants.NODESET));
if (nodeList.getLength() == 1) {
// we've found a 'name' element with value 'john'
Node parent = nodeList.item(0).getParentNode();
// This node is the <contact> node
// use it to do anything you want, ie. get the child nodes and print their info
} else {
// there was no such element
}
DocumentBuilderFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder=factory.newDocumentBuilder();
Document doc=builder.parse(文件);//文件的uri
XPathFactory XPathFactory=XPathFactory.newInstance();
XPath=xPathfactory.newXPath();
XPathExpression expr=xpath.compile(“/contactInfo/contact/name[text()='john']”);
NodeList NodeList=(NodeList)(expr.evaluate(doc,XPathConstants.NODESET));
if(nodeList.getLength()==1){
//我们找到了一个值为“john”的“name”元素
Node parent=nodeList.item(0.getParentNode();
//这个节点就是这个节点
//使用它可以做任何你想做的事情,例如,获取子节点并打印它们的信息
}否则{
//没有这样的因素
}
您可能想考虑下面的情况:<代码> NoDistist.GigLimthHe()/代码>可能返回> 1。只需获取每个节点的父节点并显示它
可能有更好的XPath表达式可以直接查找
元素,但是上面的方法可以工作
使用
系统构建扫描仪
。在
中。如果你有XML解析器,为什么还要麻烦扫描仪呢?它给你一个银盘上的每个元素,以及它的名字,所以你所需要做的就是比较字符串!这是作业的一部分,我必须能够搜索一个名字,然后其他所有的东西都能找到。@TimCalara-但这并不意味着你必须使用扫描仪。它不是一个搜索工具。@dasblinkenlight我觉得它的任务是接受用户输入并使用该输入查找XML元素。
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file); // uri to your file
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/contactInfo/contact/name[text()='john']");
NodeList nodeList = (NodeList)(expr.evaluate(doc, XPathConstants.NODESET));
if (nodeList.getLength() == 1) {
// we've found a 'name' element with value 'john'
Node parent = nodeList.item(0).getParentNode();
// This node is the <contact> node
// use it to do anything you want, ie. get the child nodes and print their info
} else {
// there was no such element
}