嗨,我是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.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 javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class contactInfo
{
String name;
String address;
int phone;
String group;
public String getName()
{
return name;
}
@XmlElement
public void setName(String name)
{
this.name = name;
}
public String getAddress()
{
return address;
}
@XmlElement
public void setAddress(String address)
{
this.address = address;
}
public int getPhone()
{
return phone;
}
@XmlElement
public void setPhone(int phone)
{
this.phone = phone;
}
public String getGroup()
{
return group;
}
@XmlElement
public void setGroup(String group)
{
this.group = group;
}
}
我的主课
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();
}
}
}
我的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>
我希望能够使用扫描仪搜索像蒂姆这样的名字,然后使用该名字,显示与该名字相关的所有信息。例如,如果在扫描仪中键入了john,则会显示john的地址、电话和组。
反之亦然,包括地址、组和电话
最近更新了我的代码和xml文件
您可以使用< code>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
}
您可能需要考虑<code>节点列表的情况。getLength()可能返回
可能有一个更好的 XPath 表达式来查找
下面是解释 XPath 语法的资源。
我正在尝试用javaoop编写一个程序,在这个程序中我主要创建一些人(每个人都有姓名、年龄、身份:是否受雇)。 我想按姓名搜索这些人,并显示所有细节。 例如,如果有一个叫约翰的人,我通过名字找到了他,我想列出所有的细节(状态、年龄等等)。 我尝试在Person类中实现这个方法。< br >我不知道创建一个包含所有人和姓名的地图,然后在其中进行搜索是否更好。 以下是我的代码: 人员类: 雇佣类别:
问题内容: 这是一项学术任务,我们将获得一个非常大的XML文件,其中包含数百个此类条目。对于每个项目,我们都应列出经理的ID,将项目添加到列表中的最后一个人员的人员ID以及当前的项目数。我已阅读并重新阅读了Oracle DOM API和各种Node API。我们正在使用JAVA,我一生都无法弄清楚如何搜索每个节点的各个“字段” 。以下是我们提供的数据示例。 我尝试做类似的事情: 并弄乱了这段代码一
我有一个注释@API,它分配给Java Spring中一个控制器中的所有路由,即RequestMapping。我想做的是,首先扫描一个包中用@controller注释的所有类,在扫描所有控制器类之后,我只想在这些控制器注释的类中扫描带有注释@API的方法。 我如何在Java中使用反射来实现这一点?
这是我目前所掌握的:
我尝试搜索列表中的某个特定名称(如果它在列表中),然后打印该对象。
我实际上是一个新手到Java,并试图做一个小项目。所以,在我的项目中,我想让用户输入一个句子,我想让程序在句子中搜索特定的单词,并基于此给出输出。我使用NetBeans开发我的应用程序。 我的代码是这样的 我知道这段代码没有意义,也不会运行,但我这样说是为了让人们对我试图实现的目标有一个大致的了解。 请帮帮我.