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();
}
}
}
Related
Hello so i've looked this question up alot but I couldn't find a solution that worked. I'm basically trying to remove the "job" node as seen declared in line 7 and removed in line 13. There's 0 runtime errors but the node doesn't get removed.
NodeList rootNodes = xml.getElementsByTagName("jobs");
Node rootNode = rootNodes.item(0);
Element rootElement = (Element) rootNode;
NodeList jobsList = rootElement.getElementsByTagName("job");
for (int i = 0; i < jobsList.getLength(); i++) {
Node job = jobsList.item(i);
Element jobElement = (Element) job;
if(jobElement.getAttribute("id").equals(
msgEvent.getMessage().getContentRaw().split(" ")[2]))
{
rootNode.removeChild(job);
msgEvent.getChannel().sendMessage("Removed Job " + jobElement.getAttribute("id") + " (Summary: '" + jobElement.getAttribute("summary") + "')").complete();
}
}
Here's the XML
<?xml version = "1.0"?>
<jobs>
<job payment = "50000" poster="171048434529337344" collect = "asdf" id = "1" summary="asdfd" expires="5/10/18"> </job>
<job payment = "10000" poster="171048434529337344" collect = "asdf" id = "2" summary="asdf" expires="5/10/18"> </job>
</jobs>
since this is too large for comment, Here is my test code and results:
public static void main(String[] args) {
try (InputStream is = Files.newInputStream(Paths.get("C://Temp/xx.xml"))) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document xml = builder.parse(new InputSource(is));
NodeList rootNodes = xml.getElementsByTagName("jobs");
Node rootNode = rootNodes.item(0);
Element rootElement = (Element) rootNode;
NodeList jobsList = rootElement.getElementsByTagName("job");
System.out.println("list before removal");
for (int i = 0; i < jobsList.getLength(); i++) {
Node job = jobsList.item(i);
Element jobElement = (Element) job;
System.out.println(jobElement.getAttribute("id"));
}
for (int i = 0; i < jobsList.getLength(); i++) {
Node job = jobsList.item(i);
Element jobElement = (Element) job;
if (jobElement.getAttribute("id").equals("1")) {
rootNode.removeChild(job);
}
}
System.out.println("list after removal");
jobsList = rootElement.getElementsByTagName("job");
for (int i = 0; i < jobsList.getLength(); i++) {
Node job = jobsList.item(i);
Element jobElement = (Element) job;
System.out.println(jobElement.getAttribute("id"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
output:
list before removal
1
2
list after removal
2
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);
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();
}
}
Took a long time searching and watching videos.
I'm trying to access the course subjects ID
This is my xml code
<list>
<Asignatura>
<id>1</id>
<nombre>Programación</nombre>
<curso>
<id>1</id>
<nombre>1º DAM</nombre>
<listaAsignaturas>
<Asignatura reference="../../.."/>
<Asignatura>
<id>2</id>
<nombre>Bases de datos</nombre>
<curso reference="../../.."/>
<listaAlumnos/>
</Asignatura>
<Asignatura>
<id>3</id>
<nombre>Formación y orientación laboral</nombre>
<curso reference="../../.."/>
<listaAlumnos/>
</Asignatura>
<Asignatura>
<id>4</id>
<nombre>Entornos de desarrollo</nombre>
<curso reference="../../.."/>
<listaAlumnos/>
</Asignatura>
</listaAsignaturas>
</curso>
<listaAlumnos/>
</Asignatura>
</list>
And here my code in java
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("./datos/Asignaturas.xml");
document.getDocumentElement().normalize();
NodeList Asignatura = document.getElementsByTagName("Asignatura");
for (int i = 0; i < Asignatura.getLength(); i++) {
Node c = Asignatura.item(i);
if (c.getNodeType() == Node.ELEMENT_NODE) {
Element elemento = (Element) c;
int id = Integer.parseInt(getValorHijo("id", elemento));
String nombre = getValorHijo("nombre", elemento);
//int idCurso = Integer.parseInt(getValorHijo("curso", elemento));
curso = new Curso();
curso.setId(idCurso);
curso = (Curso) FileXMLDAOFactory.getInstance().getCursoDAO().buscar(curso);
}
}
} catch (Exception e) {
e.printStackTrace();
}
I have to say it works, pick up the ID and name of the subject.
But I can not pick up the ID or name of the course subject that is within.
Im not have idea how can get it :(
I tried a slighty different approach with the same xml input file with the following code.
public static void main(String[] args) {
List<Assignatura> assignaturas = new ArrayList<Assignatura>();
List<Curso> cursos = new ArrayList<Curso>();
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder loader = factory.newDocumentBuilder();
Document document = loader.parse("datos.xml");
DocumentTraversal traversal = (DocumentTraversal) document;
NodeIterator iterator = traversal.createNodeIterator(
document.getDocumentElement(), NodeFilter.SHOW_ALL, new ListAsignaturasFilter(), true);
for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
Element el = (Element) n;
NodeList assignments = el.getElementsByTagName("Asignatura");
for(int i=0; i<assignments.getLength(); i++){
Node currentNode = assignments.item(i);
NodeList childs = currentNode.getChildNodes();
String id = getValorHijo(childs, "id");
String nombre = getValorHijo(childs, "nombre");
if(!id.isEmpty() || !nombre.isEmpty())
assignaturas.add(new Assignatura(id, nombre));
}
}
NodeIterator itCurso = traversal.createNodeIterator(
document.getDocumentElement(), NodeFilter.SHOW_ALL, new CursoFilter(), true);
for (Node n = itCurso.nextNode(); n != null; n = itCurso.nextNode()) {
Element el = (Element) n;
NodeList cursos = el.getChildNodes();
String id = getValorHijo(cursos, "id");
String nombre = getValorHijo(cursos, "nombre");
if(!id.isEmpty() || !nombre.isEmpty())
cursos.add(new Curso(id, nombre));
}
for(Assignatura assignatura : assignaturas){
System.out.println(assignatura);
}
for(Curso curso : cursos){
System.out.println(curso);
}
}catch (Exception e) {
e.printStackTrace();
}
}
private static String getValorHijo(NodeList childs, String data){
String search="";
if(childs.getLength()>0)
for(int j=0; j<childs.getLength(); j++){
if(childs.item(j).getNodeName().equals(data)){
return childs.item(j).getTextContent();
}
}
return search;
}
private static final class ListAsignaturasFilter implements NodeFilter {
public short acceptNode(Node n) {
if (n instanceof Element) {
if (((Element) n).getTagName().equals("listaAsignaturas")) {
return NodeFilter.FILTER_ACCEPT;
}
}
return NodeFilter.FILTER_REJECT;
}
}
private static final class CursoFilter implements NodeFilter {
public short acceptNode(Node n) {
if (n instanceof Element) {
if (((Element) n).getTagName().equals("curso")) {
return NodeFilter.FILTER_ACCEPT;
}
}
return NodeFilter.FILTER_REJECT;
}
}
As you can see I created two lists to memorize "Assignatura" an "Curso" object which are simple POJO with two attributes id and nombre. At the end of the main method I display the content of these lists and I've got the id and nombre information of element "Curso" besides all "Asignatura" elements. Hope this code help you !
Just for the record. The use of DOM was compulsory ? Because, it would have been easier to use JAXB.
In my application, I have an XML file and I want to parse the XML file and extract data from the XML tags. Here is my XML file.
<array>
<recipe>
<name> Crispy Fried Chicken </name>
<description> Deliciously Crispy Fried Chicken</description>
<prepTime>1.5 hours </prepTime>
<instructions>instruction steps</instructions>
<ingredients>
<item>
<itemName>Chicken Parts</itemName>
<itemAmount>2 lbs</itemAmount>
</item>
<item>
<itemName>Salt & Peppers</itemName>
<itemAmount>As teste</itemAmount>
</item>
</ingredients>
</recipe>
<recipe>
<name> Bourben Chicken </name>
<description> A good recipe! A tad on the hot side!</description>
<prepTime>1 hours </prepTime>
<instructions>instruction steps</instructions>
<ingredients>
<item>
<itemName>Boneless Chicken</itemName>
<itemAmount>2.5 lbs</itemAmount>
</item>
<item>
<itemName>Olive Oil</itemName>
<itemAmount>1 -2 tablespoon</itemAmount>
</item>
<item>
<itemName>Olive Oil</itemName>
<itemAmount>1 -2 tablespoon</itemAmount>
</item>
</ingredients>
</recipe>
</array>
I have used DOM parser to parse the above xml file and I have extracted data from <name>, <description>, <prepTime> and <instructions> tags BUT I don't know how to extract data from <ingredients> TAG. You can see my code that I have developed for DOM parser. Here is my DOM parser
public class DOMParser
{
// parse Plist and fill in arraylist
public ArrayList<DataModel> parsePlist(String xml)
{
final ArrayList<DataModel> dataModels = new ArrayList<DataModel>();
//Get the xml string from assets XML file
final Document doc = convertStringIntoXML(xml);
// final NodeList nodes_array = doc.getElementsByTagName("array");
//Iterating through the nodes and extracting the data.
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
if (node instanceof Element)
{
DataModel model = new DataModel();
NodeList childNodes = node.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++)
{
Node cNode = childNodes.item(j);
if (cNode instanceof Element)
{
String content = cNode.getLastChild().getTextContent().trim();
if(cNode.getNodeName().equalsIgnoreCase("name"))
model.setName(content);
else if(cNode.getNodeName().equalsIgnoreCase("description"))
model.setDescription(content);
else if(cNode.getNodeName().equalsIgnoreCase("prepTime"))
model.setPrepTime(content);
else if(cNode.getNodeName().equalsIgnoreCase("instructions"))
model.setInstructions(content);
}
}
dataModels.add(model);
}
}
return dataModels;
}
// Create xml document object from XML String
private Document convertStringIntoXML(String xml)
{
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
}
catch (ParserConfigurationException e)
{
System.out.println("XML parse error: " + e.getMessage());
return null;
}
catch (SAXException e)
{
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
}
catch (IOException e)
{
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}
}
You need to iterate ingredients child nodes like you do it for recipe tag.
But the more easy way is to use XPath.
you can change your code as below.
public ArrayList<DataModel> parsePlist(String xml)
{
final ArrayList<DataModel> dataModels = new ArrayList<DataModel>();
//Get the xml string from assets XML file
final Document doc = convertStringIntoXML(xml);
//final NodeList nodes_array = doc.getElementsByTagName("array");
//Iterating through the nodes and extracting the data.
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
if (node instanceof Element)
{
DataModel model = new DataModel();
NodeList childNodes = node.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++)
{
Node cNode = childNodes.item(j);
if (cNode instanceof Element)
{
String content = cNode.getLastChild().getTextContent().trim();
if(cNode.getNodeName().equalsIgnoreCase("name"))
model.setName(content);
else if(cNode.getNodeName().equalsIgnoreCase("description"))
model.setDescription(content);
else if(cNode.getNodeName().equalsIgnoreCase("prepTime"))
model.setPrepTime(content);
else if(cNode.getNodeName().equalsIgnoreCase("instructions"))
model.setInstructions(content);
else if(cNode.getNodeName().equalsIgnoreCase("ingredients"))
{
Element ingredEle = (Element)cNode;
NodeList ingredList = ingredEle
.getElementsByTagName("ingredients");
for (int i = 0; i < ingredList.getLength(); i++)
{
Element item = (Element)ingredList.item(i);
if(item.hasChildNodes())
{
NodeList itemList = item.getElementsByTagName("item");
for (int j = 0; j < itemList.getLength(); j++)
{
Element itemEle = (Element)itemList.item(j);
if (getNodeValue(itemEle, "itemName") != null)
{
String name = getNodeValue(itemEle, "itemName");
//set name here
}
if (getNodeValue(itemEle, "itemAmount") != null)
{
String amount = getNodeValue(itemEle,"itemAmount");
//set amount here
}
}
}
}
}
}
dataModels.add(model);
}
}
return dataModels;
}
private String getNodeValue(Element element, String elementTemplateLoc) {
NodeList nodes = element.getElementsByTagName(elementTemplateLoc);
return getTextNodeValue(nodes.item(0));
}
Hope this will work for you