我需要解析存储在blobstore中的XML文件。我该怎么做?
这是我到目前为止所做的事情:
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile file = fileService.getBlobFile(new BlobKey(key));
我无法使用javax.xml
包解析XML文件,或者我可以吗?如果付诸实施,该包中的类需要引用java.io.File
对象。但我没有。
这就是我到目前为止所做的事情:(不是在服务器上,而是在本地)
File blobKeys = new File("/home/non-admin/NetBeansProjects/Personal Site_Testers/web/xml/xml_1.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(blobKeys);
Element root = doc.getDocumentElement();
Element firstName = doc.createElement("first-name");
firstName.setTextContent(name);
root.appendChild(firstName);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("/home/non-admin/NetBeansProjects/Personal Site_Testers/web/xml/xml_1.xml"));
transformer.transform(source, result);
注意:有3个xml文件上传到blobstore。那些xml文件只有一个root标签。我想获取xml引用并解析它们以根据请求多次附加子节点。
答案 0 :(得分:0)
如果你想解析* .xml,我认为jdom2可能更方便我在app引擎中使用它并且它可以工作。
但是,您可以阅读FileService API文档,并且有一个如何读取和写入文件的示例。如果你可以获得一个InputStream或Reader,那么你可以使用javax.xml来解析InputStream或Reader中的xml内容。
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile readableFile = new AppEngineFile("your_file_name");
FileReadChannel readChannel = fileService.openReadChannel(readableFile,
false);
InputStream input = Channels.newInputStream(readChannel);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(input);
Element root = doc.getDocumentElement();
Element firstName = doc.createElement("first-name");
firstName.setTextContent("content");
root.appendChild(firstName);
// Now write
GSFileOptionsBuilder optionsBuilder = new GSFileOptionsBuilder()
.setBucket("mybucket").setKey("myfile")
.setMimeType("text/html").setAcl("public_read")
.addUserMetadata("myfield1", "my field value"); // change as
// your need
AppEngineFile writableFile = fileService.createNewGSFile(optionsBuilder
.build());
FileWriteChannel writeChannel = fileService.openWriteChannel(
writableFile, false);
OutputStream output = Channels.newOutputStream(writeChannel);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(doc);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(output);
transformer.transform(source, result);