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);
Related
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();
}
}
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();
}
}
I'm trying parse a webpage in XML and print data in my logcat, but my output is empty.
This is my XML structure:
<?xml version="1.0"?>
<FLIGHTS>
<FLIGHT airport="b: 3 "
logo="IG"
code="IG"
numero="1234"
carrier="AirBerlin"
city="NEW YORK"
terminal="Terminal A"
sched="08:40"
expect="09:09"
tipo_volo="L" stato="J"
</FLIGHT>
<FLIGHT airport="c: 3 "
....
.....more...
</FLIGHT>
</FLIGHTS>
and this is my Android code inside AsyncTask:
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL("http://myurl");
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
NodeList nodes = doc.getElementsByTagName("FLIGHT");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
// NodeList title = element.getElementsByTagName("airport");
// Element line = (Element) title.item(0);
// a.add(line.getTextContent());
Log.d("LOG...", "" + element.getTextContent());
}
} catch (Exception e) {
e.printStackTrace();
}
inside the AndroidManifest, i have the internet permission!
Thank you!
If the XML were correct, attributes XXX="..." are got differently:
Element element = (Element) nodes.item(i);
String airport = element.getAttribute("airport");
if (airport != null) { ...
Your code sample works. Java is case sensitive. Are you sure your XML tag name is correct?
Here is a working example using a XML example of w3schools:
try {
URL url = new URL("http://www.w3schools.com/xml/note.xml");
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
NodeList nodes = doc.getElementsByTagName("note");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
// NodeList title = element.getElementsByTagName("airport");
// Element line = (Element) title.item(0);
// a.add(line.getTextContent());
System.out.println(element.getTextContent());
}
} catch (Exception e) {
e.printStackTrace();
}
And now using your XML example and Joop Eggen's answer:
try {
URL url = new URL("http://myurl");
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
NodeList nodes = doc.getElementsByTagName("FLIGHT");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
String airport = element.getAttribute("airport");
System.out.println("element " + i + ": airport=" + airport);
}
} catch (Exception e) {
e.printStackTrace();
}
Example using a simple file:
test.xml:
<?xml version="1.0"?>
<FLIGHTS>
<FLIGHT airport="b: 3 " logo="IG" code="IG" numero="1234"
carrier="AirBerlin" city="NEW YORK" terminal="Terminal A" sched="08:40"
expect="09:09" tipo_volo="L" stato="J">
</FLIGHT>
</FLIGHTS>
Example.java:
import java.io.File;
import java.io.FileInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class Example {
public static void main(String[] args) {
File f = new File("test.xml");
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new FileInputStream(f));
NodeList nodes = doc.getElementsByTagName("FLIGHT");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
String airport = element.getAttribute("airport");
System.out.println("element " + i + ": airport='" + airport + "'");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
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"));
}
}
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();
}
}
}