I'm trying to parse SVG file to get paths using Xpath within android application. Native java parse the path in following way.
try {
Document document = builder.parse(
new FileInputStream("c:\\employees.xml"));
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I try to do using FileDescriptor as follows.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
AssetManager assetManager = getBaseContext().getAssets();
AssetFileDescriptor assetFileDescriptor = null;
try {
assetFileDescriptor = assetManager.openFd("android.svg");
} catch (IOException e) {
e.printStackTrace();
}
FileDescriptor fileDescriptor = assetFileDescriptor.getFileDescriptor();
FileInputStream stream = new FileInputStream(fileDescriptor);
try {
Document document = builder.parse(stream);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
However my app stopped working. What's wrong in my code?
You do not need FileDescriptor. Try as follows.
InputStream input = assetManager.open("android.svg"); //From your asset folder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
And parse your input to builder.
Document document = builder.parse(input);
Related
In my app I need to read the content of an element from an xml file.
So I write in my LocalRead.java class the method "getValueOfElement" in this way:
[...]
public String getValueOfElement (String filename, String what){
try{
File xmlDocument = new File ("/Unknow_Path/"+filename);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(xmlDocument);
String lookingFor = document.getElementsByTagName(what).item(0).getTextContent();
return lookingFor;
} catch (FileNotFoundException e) {
System.err.println("----------------- File not found -----------------");
e.printStackTrace();
return "";
} catch (ParserConfigurationException e) {
System.err.println("----------------- Error creating DocumentBuilder -----------------");
e.printStackTrace();
return "";
} catch (SAXException e) {
System.err.println("----------------- Error creating the document(Sax) -----------------");
e.printStackTrace();
return "";
} catch (IOException e) {
System.err.println("----------------- Error creating the document(IO) -----------------");
e.printStackTrace();
return "";
}
}
[...]
As you can see, when I create the File "xmlDocument" I don't know the path where my xml file is. I used this class to create the file.
import android.content.Context;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileBuilder {
private String xmlContent;
private String filename;
private Context context;
private FileOutputStream outputStream;
public FileBuilder(Context context){
this.context = context;
}
public boolean createUserFile(String username, String password){
this.xmlContent = "<?xml version='1.0' encoding='UTF-8'?>\n" +
"<giocatore>\n" +
"<username>"+username+"</username>\n" +
"<password>"+password+"</password>\n" +
"</giocatore>";
this.filename = "[D&D]User.xml";
try{
outputStream = context.openFileOutput(filename, context.MODE_PRIVATE);
outputStream.write(xmlContent.getBytes());
outputStream.close();
System.out.println("----------------- File created -----------------");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
How can I find out what the path is?
Like CommonsWare says in the comments, Document can parse an InputStream. So you can load the file as a Document using openFileInput(). Here the complete code:
[...]
public String getValueOfElement (String filename, String what){
try{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(context.openFileInput(filename));
String lookingFor = document.getElementsByTagName(what).item(0).getTextContent();
return lookingFor;
} catch (FileNotFoundException e) {
System.err.println("----------------- File not found -----------------");
e.printStackTrace();
return "";
} catch (ParserConfigurationException e) {
System.err.println("----------------- Error creating DocumentBuilder -----------------");
e.printStackTrace();
return "";
} catch (SAXException e) {
System.err.println("----------------- Error creating the document(Sax) -----------------");
e.printStackTrace();
return "";
} catch (IOException e) {
System.err.println("----------------- Error creating the document(IO) -----------------");
e.printStackTrace();
return "";
}
}
[...]
Remember that openFileInput() need a Context.
Thanks to #CommonsWare for the answer
I have been recently trying to read from a xml file. I believe I am parsing correctly but it returns null,however not always.I received the input that I want 1 out of 100 executions, with no drastic changes on code.This is the code that receives the file path of xml file(also file in code)
public Document getXmlDoc(String filePath) {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
Document doc = null;
try {
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(new File(filePath));
doc.getDocumentElement().normalize();
System.out.println(doc.getDocumentElement().getNodeValue());//null
System.out.println(doc.getDocumentElement().getChildNodes().item(1));//null
System.out.println(doc.getDocumentElement().getLastChild().getAttributes().getNamedItem("id"));//not null and correct
System.out.println(doc.getDocumentElement().getElementsByTagName("entry").item(1));//null
} catch (ParserConfigurationException e) {
e.printStackTrace();//pipe these
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return doc;
}
Also I call my method here and turn my node to string
NodeList nList = getXmlDoc(newFilePath).getElementsByTagName("entry");
System.out.println(nodeToString(nList.item(i)));
Where nList is a node list and nodeToString method is like this:
private String nodeToString(Node node){
StringWriter sw = new StringWriter();
try{
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
t.transform(new DOMSource(node),new StreamResult(sw));
} catch (TransformerException e) {
e.printStackTrace();
}
return sw.toString();
}
I am trying to 'GET' a rss feed.
public RssFeed(String url) {
_url = url;
String res = this.api.get(url);
ByteArrayInputStream bis = new ByteArrayInputStream(res.getBytes());
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
XMLDecoder decoder = new XMLDecoder(bis);
try {
Object xml = decoder.readObject();
_response = xml.toString();
} catch(Exception e) {
e.printStackTrace();
} finally {
decoder.close();
}
}
When I check what's inside of 'res'. It appears to get this entire XML.
But then, I am trying to decode it and I get:
java.lang.IllegalArgumentException: Unsupported element: rss
Can someone help me with that? I am new to Java.
Thanks!
XMLDecoder is meant to be used on elements created by XMLEncoder. Since you're scraping this XML from the web, the elements in this XML may not be valid according to these classes. Use a more generic XML parser, such as DocumentBuilder::parse() to handle this.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
try {
builder.parse(url);
} catch (IOException e) {
e.printStackTrace();
} catch (SAXParseException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
I am trying to split a pdf document through org.apache.pdfbox.multipdf.Splitter and need to perform certain file operations on this single page PDDocument,
How can I convert PDDocument to File Object in java?
Very simple. I am using 1.8.16
try {
PDDocument document = PDDocument.load(new File(filename));
// do what ever you want
document.save(newfilename);
} catch (IOException | BadSecurityHandlerException | CryptographyException e) {
e.printStackTrace();
}
finally {
if(document != null )
try {
document.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//return tmpFile != null ? tmpFile.getAbsolutePath() : null;
return tmpFilename;
}
with Apache commons
InputStream is = null
try {
PDDocument document = PDDocument.load(filePath);
File targetFile = new File("nameoffile.pdf");
PDStream ps = new PDStream(document);
is = ps.createInputStream();
FileUtils.copyInputStreamToFile(is, targetFile);
} catch (IOException io) {} finally {
if (is != null)
IOUtils.closeQuietly(is);
}
When I run HP fortify the following code is given as a XML External Entity injection.Problem line is specified as Error Line.Any Help is appreciated.
private Document parseXmlString(String stringname, boolean validating) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(validating);
ByteArrayInputStream is = new ByteArrayInputStream(stringname.getBytes());
Document doc = factory.newDocumentBuilder().parse(is);//Error Line
return doc;
} catch (SAXException e) {
// A parsing error occurred; the xml input is not valid
} catch (ParserConfigurationException e) {
} catch (IOException e) {
}
return null;
}
I hope this is what you are looking for:
https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing