I have models designed to store xml files:
public class FileUpload extends Model {
@Id
public Long id;
public String fileName;
}
A file is simply an xml with a root and lots of parent and child nodes.
public class FileElement extends Model {
@Id
public Long id;
public String name;
public String text;
@ManyToOne
public FileUpload fileUpload; // Each FileElement has a reference to the FileUpload (So that I know which FileElements belong to a FileUpload).
@OneToMany
public List<FileElementAttribute> attributes;
@OneToMany(mappedBy="parentElement")
public List<FileElement> childElements;
@ManyToOne
public FileElement parentElement; // if parentElement == null, FileElement is a root element.
}
public class FileElementAttribute extends Model {
@Id
public Long id;
public String attributeName;
public String attributeValue;
@ManyToOne
public FileElement fileElement; // A Xml node can have multiple attributes.
}
This is the method I call to save an xml to the database.
public static FileElement create(Node node, FileElement parentElement, FileUpload fileUpload) {
if (node instanceof Element) {
FileElement fe = new FileElement();
fe.name = node.getNodeName();
fe.text = "";
fe.fileUpload = fileUpload;
fe.parentElement = parentElement;
if(node.getChildNodes().getLength() == 1) fe.text = node.getTextContent().trim();
fe.save();
for (int i = 0; i < node.getAttributes().getLength(); i++) {
FileElementAttribute fea = new FileElementAttribute();
fea.attributeName = node.getAttributes().item(i).getNodeName();
fea.attributeValue = node.getAttributes().item(i).getNodeValue();
fea.fileElement = fe;
fea.save();
}
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
FileElement fec = create(node.getChildNodes().item(i), fe, fileUpload);
if (fec != null) {
fe.childElements.add(fec);
}
}
fe.update();
return fe;
} else {
return null;
}
}
This is how I use it:
FileUpload fu = new FileUpload();
fu.fileName = "First"
fu.save();
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = null;
String file = "~/MyApp/First.xml";
try (InputStream stream = new FileInputStream(file)) {
document = builder.parse(stream);
}
Node node = document.getDocumentElement();
FileElement.create(node, null, fu);
} catch (Exception e) {
Logger.error(e.toString());
}
The implementation may be too complex, I am certainly open for a better implementation of this. This was written for Java EE but I am trying my hardest to implement it to play's way.
Saving an Xml document and retrieving it wasn't a problem anymore.
I am implementing a search functionality where the user keys in a String and I will use the String to query where it is equals to FileElement.text or FileElementAttribute.attributeValue.
Once I execute the query, I'm suppose to get a list of FileElement and return its unique list of FileUpload.
The question is, how am I suppose to code that?
No comments:
Post a Comment