java XML数据加载和保存方法示例[已关闭]

f0brbegy  于 2023-11-15  发布在  Java
关注(0)|答案(1)|浏览(95)

已关闭。此问题需要更多focused。目前不接受回答。
**要改进此问题吗?**更新此问题,使其仅针对editing this post的一个问题。

4天前关闭。
Improve this question
我目前正在做一个Java项目,需要在XML文件中存储一个对象列表,然后检索该列表进行处理。
同时JSON文件读取器和加载器也是我的项目所必需的。对于一个新手来说,熟悉大量的XML库或documentBuilder库是相当困难的。
现有的很多教程要么太有条理、循序渐进,要么不够简单易懂,希望能找到一些典范性的代码。
代码或介绍的例子。

xqnpmsa8

xqnpmsa81#

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class PDXML {
    List<Person> people;
    public PDXML()
    {
        people = new ArrayList<Person>();
    }
    public List<Person> loadData(String filePath)
    {
        File f = new File(filePath);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        List<Person> lp = new ArrayList<Person>();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document d = db.parse(f); 
            d.getDocumentElement().normalize(); 
            NodeList nl = d.getElementsByTagName("Person");
            for(int i = 0; i < nl.getLength(); i++)
            {
                Node n = nl.item(i); 
                if(n.getNodeType() == Node.ELEMENT_NODE) {
                    Element element     = (Element) n;
                    Integer id          = Integer.parseInt(element.getAttribute("id")); 
                    String firstname    = element.getElementsByTagName("FirstName").item(0).getTextContent();
                    String lastname     = element.getElementsByTagName("LastName").item(0).getTextContent();
                    Person p            = new Person(id, firstname, lastname);
                    lp.add(p);
                }
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return lp;
    }
    public void saveData(String filePath)
    {
        File f = new File(filePath);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder(); 
            Document d = db.newDocument(); 
            Element rootElement = d.createElement("People");
            d.appendChild(rootElement); 
            for(Person person : people)
            {
                Element personElement = d.createElement("Person");
                personElement.setAttribute("id", Integer.toString(person.getId()));
                Element firstnameElement = d.createElement("FirstName");
                firstnameElement.appendChild(d.createTextNode(person.getFirstname()));
                personElement.appendChild(firstnameElement);
                Element lastnameElement = d.createElement("LastName");
                lastnameElement.appendChild(d.createTextNode(person.getLastname()));
                personElement.appendChild(lastnameElement);
                rootElement.appendChild(personElement);
            }
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(d); 
            StreamResult result = new StreamResult(f);
            transformer.transform(source, result); 
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) 
    {
        PDXML xml = new PDXML();
        xml.people.add(new Person(10,"Lisa", "Simpson"));
        xml.people.add(new Person(11,"Homer", "Simpson"));
        xml.people.add(new Person(12,"Maggie", "Simpson"));
        xml.saveData("resources/people1.xml");
        List<Person> newPeople = xml.loadData("resources/people.xml");
        for(Person p : newPeople)
        {
            System.out.println(p.toString());
        }
    }
}

字符串

相关问题