libgdx FileNotFoundException on android device - java

I have xml file which I need to read to load level. This file is located in assets folder.
When I run on desctop machine everything is alright. But on Android device I get FileNotFoundException when try to parse this file.
Here is code of reading method
public void readLevels() {
this.levelList = new ArrayList<Level>();
FileHandle handle = Gdx.files.internal("lvl/levels.xml");
try {
File fXmlFile = handle.file();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
try {
Document document = documentBuilder.parse(fXmlFile);
document.getDocumentElement().normalize();
NodeList nodeList = document.getElementsByTagName("level");
Level level;
for (int iterator = 0; iterator < nodeList.getLength(); iterator++) {
Node node = nodeList.item(iterator);
Element element = (Element) node;
String levelName = element.getAttribute("name");
int levelNumber = Integer.parseInt(element.getAttribute("order"));
NodeList ballList = element.getElementsByTagName("ball");
List<Ball> levelBallList = new ArrayList<Ball>();
Ball ball;
for (int iter = 0; iter < ballList.getLength(); iter++) {
Element ballIn = (Element) ballList.item(iter);
NodeList positionX = ballIn.getElementsByTagName("position-x");
NodeList positionY = ballIn.getElementsByTagName("position-y");
int x = Integer.parseInt(positionX.item(0).getChildNodes().item(0).getNodeValue());
int y = Integer.parseInt(positionY.item(0).getChildNodes().item(0).getNodeValue());
ball = new Ball(new Vector2(y, x), ballTextures[generateImage()]);
levelBallList.add(ball);
}
level = new Level(levelName, levelNumber, levelBallList);
this.levelList.add(level);
}
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}

Related

Parse Xml returns only 1 item

I want to get the File nodes of this xml document, can anyone help me with archive this issue?
I have this xml document:
<?xml version="1.0" encoding="UTF-8"?>
<Replies>
<FileList>
<File>cip13_test.rts</File>
<File>databar_lmt.rts</File>
<File>Test3.rts</File>
<File>databar2_lmt.rts</File>
<File>databar5_lmt.rts</File>
</FileList>
</Replies>
and I need to get all File-items from this.
I have this code but I get only cip13_test.rtx.
public static String GetFileList(String fileresponse) {
String xml = fileresponse;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
InputSource is = new InputSource();
String textToShow = "";
StringBuilder resultsofList = new StringBuilder();
try {
db = dbf.newDocumentBuilder();
is.setCharacterStream(new StringReader(xml));
try {
Document doc = db.parse(is);
NodeList replies = doc.getElementsByTagName("Replies");
for (int i = 0; i < replies.getLength(); i++) {
Element element = (Element) replies.item(i);
NodeList inkstatus = element.getElementsByTagName("FileList");
for (int i2 = 0; i2 < inkstatus.getLength(); i2++) {
Element element2 = (Element) inkstatus.item(i2);
NodeList inklevel = element2.getElementsByTagName("File");
for (int i4 = 0; i4 < inklevel.getLength(); i4++) {
Element element4 = (Element) inklevel.item(i4);
Element line = (Element) inklevel.item(0);
if (line == null) {
inklevel = element4.getElementsByTagName("File");
line = (Element) inklevel.item(0);
}
textToShow = getCharacterDataFromElement(line);
resultsofList.append(textToShow+",");
}
}
}
} catch (SAXException e) {
// handle SAXException
} catch (IOException e) {
// handle IOException
}
} catch (ParserConfigurationException e1) {
// handle ParserConfigurationException
}
return String.valueOf(resultsofList);
}
This line is wrong:
Element line = (Element) inklevel.item(0);
It should be
Element line = (Element) inklevel.item(i4);

Unable to delete a specific node in XML

I have an XML file and I need to delete a specific node. The node to be deleted will be defined dynamically based on the logic. I have been searching in internet for a solution but couldn't delete my node still. am getting error - NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist
Below is a sample XML File. I need to delete the node <NameValuePairs> which has <name>Local Variables</name>. Below is my sample XML Files Java Code
Sample XML File
<?xml version="1.0" encoding="UTF-8"?>
<DeploymentDescriptors xmlns="http://www.tibco.com/xmlns/dd">
<name>Test</name>
<version>1</version>
<DeploymentDescriptorFactory>
<name>RepoInstance</name>
</DeploymentDescriptorFactory>
<DeploymentDescriptorFactory>
<name>NameValuePairs</name>
</DeploymentDescriptorFactory>
<NameValuePairs>
<name>Global Variables</name>
<NameValuePair>
<name>Connections1</name>
<value>7222</value>
<requiresConfiguration>true</requiresConfiguration>
</NameValuePair>
<NameValuePair>
<name>Connections2</name>
<value>7222</value>
<requiresConfiguration>true</requiresConfiguration>
</NameValuePair>
</NameValuePairs>
<NameValuePairs>
<name>Local Variables</name>
<NameValuePair>
<name>Connections3</name>
<value>8222</value>
<requiresConfiguration>true</requiresConfiguration>
</NameValuePair>
<NameValuePair>
<name>Connections3</name>
<value>8222</value>
<requiresConfiguration>true</requiresConfiguration>
</NameValuePair>
</NameValuePairs>
</DeploymentDescriptors>
Java Code
File fDestFile = new File("myfile.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document oDoc3 = dBuilder.parse(fDestFile);
NodeList oDestFlowList = oDoc3.getElementsByTagName("NameValuePairs");
for (int m = 0; m < oDestFlowList.getLength(); m++) {
NodeList oDestchildList = oDestFlowList.item(m).getChildNodes();
for (int n = 0; n < oDestchildList.getLength(); n++) {
Node oDestchildNode = oDestchildList.item(n);
if ("name".equals(oDestchildNode.getNodeName())) {
//oDestchildNode.getParentNode().removeChild(oDestchildNode); //Not Working
//oDoc3.getDocumentElement().removeChild(oDestchildNode); //Not Working
}
}
}
}
You need create a separate reference from the parent node as an Element so that you aren't referencing the node that you are removing:
File fDestFile = new File("src/myfile.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = null;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document oDoc3 = null;
oDoc3 = dBuilder.parse(fDestFile);
NodeList oDestFlowList = oDoc3.getElementsByTagName("NameValuePairs");
// Loop through all 'NameValuePairs'
for (int m = oDestFlowList.getLength()-1; m >=0 ; m--) {
NodeList oDestchildList = oDestFlowList.item(m).getChildNodes();
// Loop through children of 'NameValuePairs'
for (int n = oDestchildList.getLength()-1; n >=0 ; n--) {
// Remove children if they are of the type 'name'
if(oDestchildList.item(n).getNodeName().equals("name")){
oDestFlowList.item(m).removeChild(oDestchildList.item(n));
// For debugging
System.out.println(oDestchildList.item(n).getNodeName());
}
}
}
Source source = new DOMSource(oDoc3);
Result result = new StreamResult(fDestFile);
Transformer transformer = null;
transformer = TransformerFactory.newInstance().newTransformer();
// Transform your XML document (i.e. save changes to file)
transformer.transform(source, result);
} catch (Exception e) {
// Catch the exception here
e.printStackTrace();
}
}
If you are still having issues, then I would think that it is an issue with the node types. This was working for me before I put the check in for 'oDestchildNode.getNodeType()' but I would look at what type of node you are returning and go from there.
Here is the final piece of code that finally worked
public static void main(String[] args) {
File fXmlSubFile = new File("Sub.xml");
File fXmlOriginalFile = new File("Original.xml");
File fDestFile = new File("myfile.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
FileChannel source = null;
FileChannel destination = null;
XPath xPath = XPathFactory.newInstance().newXPath();
try{
if (!fDestFile.exists()) {
fDestFile.createNewFile();
}
source = new FileInputStream(fXmlOriginalFile).getChannel();
destination = new FileOutputStream(fDestFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
dBuilder = dbFactory.newDocumentBuilder();
Document oSubDoc = dBuilder.parse(fXmlSubFile);
Document oDestDoc = dBuilder.parse(fDestFile);
oSubDoc.getDocumentElement().normalize();
oDestDoc.getDocumentElement().normalize();
String sDestExpression = "/DeploymentDescriptors/NameValuePairs";
String sSubExpression = "/NameValuePairs";
NodeList nodeDestList = (NodeList) xPath.compile(sDestExpression).evaluate(oDestDoc, XPathConstants.NODESET);
NodeList nodeSubList = (NodeList) xPath.compile(sSubExpression).evaluate(oSubDoc, XPathConstants.NODESET);
for (int i = nodeDestList.getLength()-1; i >=0 ; i--) {
Node oDestNode = nodeDestList.item(i);
if (oDestNode.getNodeType() == Node.ELEMENT_NODE) {
Element oDestElement = (Element) oDestNode;
for (int j =0; j<nodeSubList.getLength(); j++) {
Node oSubNode = nodeSubList.item(j);
if (oSubNode.getNodeType() == Node.ELEMENT_NODE) {
Element oSubElement = (Element) oSubNode;
if(oDestElement.getElementsByTagName("name").item(0).getTextContent().equals(oSubElement.getElementsByTagName("name").item(0).getTextContent())){
oDestNode.getParentNode().removeChild(oDestNode);
}
}
}
}
}
Source src = new DOMSource(oDestDoc);
Result result = new StreamResult(fDestFile);
Transformer transformer = null;
transformer = TransformerFactory.newInstance().newTransformer();
// Transform your XML document (i.e. save changes to file)
transformer.transform(src, result);
}catch(Exception ex){
System.out.println("error:"+ex.getMessage());
ex.printStackTrace();
}
}

parse image in dom parser using jsoup in android

i am trying to get the rss feed of this website:
http://www.phonearena.com/feed
here is my domparser activity:
public class DOMParser {
private RSSFeed _feed = new RSSFeed();
public RSSFeed parseXml(String xml) {
URL url = null;
try {
url = new URL(xml);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
DocumentBuilderFactory dbf;
dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nl = doc.getElementsByTagName("item");
NodeList itemChildren = null;
Node currentItem = null;
Node currentChild = null;
int length = nl.getLength();
for (int i = 0; i < length; i++) {
currentItem = nl.item(i);
RSSItem _item = new RSSItem();
NodeList nchild = currentItem.getChildNodes();
int clength = nchild.getLength();
for (int j = 0; j < clength; j++) {
currentChild = nchild.item(j);
String theString = null;
String nodeName = currentChild.getNodeName();
theString = nchild.item(j).getFirstChild().getNodeValue();
if (theString != null) {
if ("title".equals(nodeName)) {
_item.setTitle(theString);
}
else if ("description".equals(nodeName)) {
_item.setDescription(theString);
// Parse the html description to get the image url
String html = theString;
org.jsoup.nodes.Document docHtml = Jsoup
.parse(html);
Elements imgEle = docHtml.select("img");
_item.setImage(imgEle.attr("src"));
}
else if ("pubDate".equals(nodeName)) {
String formatedDate = theString.replace(" +0000",
"");
_item.setDate(formatedDate);
}
}
}
_feed.addItem(_item);
}
} catch (Exception e) {
}
return _feed;
}
}
everything is working fine except the image which i am trying to get through jsoup.
can anybody tell what i am doing wrong or missing?
The variable theString needs to be unescaped before passing it to Jsoup.
else if ("description".equals(nodeName)) {
_item.setDescription(theString);
// Unescape then Parse the html description to get the image url
Element imgEle = Jsoup.parse( //
Parser.unescapeEntities( //
Parser.xmlParser().parseInput(theString, "").outerHtml(), //
true //
)) //
.select("img").first();
if (imgEle != null) {
_item.setImage(imgEle.attr("src"));
}
}

How do I read in a file path from an XML file

I am trying to read in a file path from an XML file in java, but I am getting a file not found exception. I am not sure how to fix this. Any help would be appreciated.
This is the XML file:
<adapters>
<adapter>
<class>adapters.CSVFileAdapter</class>
<properties>
<property name="filename">C:\test.csv</property>
</properties>
</adapter>
<adapter>
<class>adapters.SNMPAdapter</class>
<properties>
<property name="target">10.100.85.135</property>
<property name="port">134</property>
</properties>
</adapter>
</adapters>
This is my java code:
public class XMLConfigurationReader {
public static List<String> load()
{
List<String> adpList = new ArrayList<String>();
try{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("C:/myProject/adapters.xml"));
doc.normalize();
NodeList rootNodes = doc.getElementsByTagName("adapters");
Node rootNode = rootNodes.item(0);
Element rootElement = (Element) rootNode;
rootNodes = rootElement.getElementsByTagName("class");
for(int k=0; k<rootNodes.getLength(); k++){
Node theAdapter = rootNodes.item(k);
Element adpElement = (Element) theAdapter;
adpList.add(adpElement.getTextContent());
}
rootNodes = doc.getElementsByTagName("properties");
for (int i = 0; i < rootNodes.getLength(); i++) { // loop for properties
Node nodeData = rootNodes.item(i);
Element elementColumnDetails = (Element) nodeData;
NodeList nodeListRow = elementColumnDetails.getElementsByTagName("property");
for (int j = 0; j < nodeListRow.getLength(); j++) { // loop for property
Node nodeRow = nodeListRow.item(j);
Element elementRow = (Element) nodeRow;
if(elementRow.getAttribute("property") != null){
String property = elementRow.getTextContent().trim();
}
}
}
}catch(ParserConfigurationException e){
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return adpList;
}
}
Problem with your code is in this line
adaptersList.item(0).getChildNodes().item(0).getNodeValue();
it should be replaced with
adaptersList.item(0).getTextContent();
in order to give you that pathname.
Firstly to read a file:
public class FileRead {
static String string = File.separator;
public static void main(String[] args) {
File file = new File("C:"+string+"myProject"+string+"adapters.xml");
System.out.println(file.getName());
}
}
Then try to test below code will help you to get file Name from xml:
NodeList nodeListData = xmlTableName.getElementsByTagName("properties");
for (int k = 0; k < nodeListData.getLength(); k++) { // loop for properties
Node nodeData = nodeListData.item(k);
Element elementColumnDetails = (Element) nodeData;
NodeList nodeListRow = elementColumnDetails.getElementsByTagName("property);
for (int l = 0; l < nodeListRow.getLength(); l++) { // loop for property
Node nodeRow = nodeListRow.item(l);
Element elementRow = (Element) nodeRow;
if(elementRow.getAttribute("filename")){
filePath = elementRow.getTextContent().trim();
}
}
}

Java + reading data from XML file

What's wrong in this code? It gives me null everytime. I have no idea how to repair it, because in ordinary Java Application it works.
#WebMethod(operationName = "getColor")
public String getColor(#WebParam(name = "regNr") String regNr) {
String kolor=null;
try {
File fXmlFile = new File("/base.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("person");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) nNode;
String id = ""+ getValue("id",element);
if (regNr.equals(id)) {
color = element.getElementsByTagName("color").item(0).getTextContent();
return color;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return color;
}
I think (not sure because I don't know at which point it gives you null) you have to remove the / form the file name to become only base.xml

Categories