简体   繁体   中英

Create a simple XML-document database Java

I need some Java help.

I have got a class like this

public class Thing {
    private String name;
    private int price;

public Thing(String name, int price) {
    this.name = name;
    this.price = price;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getPrice() {
    return price;
}

public void setPrice(int price) {
    this.price = price;
}
}

And my main looks like this

public class Main {

public static void main(String[] args) {
    Thing Bowl = new Thing("Bowl", 20);
} }

What I would like to do is make a simple XML-document database. So I can add different kind of things in my database. How can I implement this kind of database in my system?

It's not correct to call what you're talking about a database. You just want to save a Java class as an XML file. Jackson is a good library that allows for both JSON and XML encode/decode and using it, can be done as so given a POJO:

ObjectMapper xmlMapper = new XmlMapper();
List<Thing> things = new ArrayList<>();

things.add(bowl);

String xmlData = xmlMapper.writeValueAsString(things);
List<Thing> thingsFromXml = xmlMapper.readValue(xmlData, new TypeReference<List<Thing>>(){});

Although the question is very broad, I'll do my best to guide you along.

An overarching system for XML consists out of various subsystems. First of all, you're going to need a way to parse the XML documents. There are many open source libraries out there that you can use. Even if you insist on writing it from scratch, referencing work that others have made is always useful.

See this: Which is the best library for XML parsing in java

Then once you have a system in place in which you can parse the documents, you'll need a way to organize the parsed data. The way to approach this is subject to the practical use of the system. For example, if you use XML as the standard format for loading data in a game and thus deal with many different types of data such as items, objects, locations and so forth. You'll want a dynamic way to reload the data, the factory design pattern would work well in this use-case.

See this: https://www.tutorialspoint.com/design_pattern/factory_pattern.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM