-1

嗨,我是 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>

我希望能够使用扫描仪搜索名称,例如 tim,然后使用该名称,显示与该名称相关的所有信息。例如,如果在扫描仪中输入了 john,则会出现 john 的地址、电话和群组。

带有地址、组和电话的 Vice Versa

最近更新了我的代码和xml文件

4

1 回答 1

4

您可以使用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
}

您可能需要考虑nodeList.getLength()可能返回 > 1 的情况。只需获取每个节点的父节点并显示它。

可能有更好的 XPath 表达式来<contact>直接查找元素,但上面的方法会起作用。

这是解释 XPath 语法的资源。

于 2013-09-02T15:50:18.520 回答