getNodeValue returnining null? - java

Hi I am trying to parse and XML file from an url, my NodeList contains values but getNodeValue for each node returns null. Can anybody help me?
This is my method where I parse the xml.
public ArrayList xmloku(String url) {
ArrayList xmllistesi = new ArrayList();
try {
URL xmlyolu = new URL(url);
DocumentBuilderFactory dFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
Document document = dBuilder.parse(new InputSource(xmlyolu
.openStream()));
document.getDocumentElement().normalize();
NodeList nodeListCountry = document
.getElementsByTagName("karikatur");
for (int i = konum; i < nodeListCountry.getLength(); i++) {
Node node = nodeListCountry.item(i);
Element elementMain = (Element) node;
xmllistesi.add(elementMain.getNodeValue());
}

Instead of getNodeValue() try using getTextContent()
for (int i = konum; i < nodeListCountry.getLength(); i++) {
Node node = nodeListCountry.item(i);
Element elementMain = (Element) node;
xmllistesi.add(elementMain.getTextContent());
}

Related

How to store xml in list in Android studio

TextView Naziv[];
TextView Id[];
int a = 0;
//ovaj primjer sam nasao na netu, treba parsirat XML
//ali nisam siguran da li treba podatke parsirat u ovoj klasi ili u nekoj drugoj
//probaj to skuzit
try{
String address = "http://www.dajsve.com/rss.ashx?svigradovi=1";
URL gradoviXmlUrl = new URL(address);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(gradoviXmlUrl.openStream());
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("Grad");
Naziv = new TextView[nodeList.getLength()];
List<Grad> gradoviLista = null;
for(int i=0; i<nodeList.getLength(); i++){
Element element = (Element) nodeList.item(i);
NodeList nazivGrada = element.getElementsByTagName("Naziv");
NodeList idGrada = element.getElementsByTagName("Id");
Element nazivGradaElement = (Element) nazivGrada.item(i);
Element idGradaElement = (Element) idGrada.item(i);
String gradNaziv = nazivGradaElement.getAttribute("Naziv");
/*Grad grad = null;
grad.setNaziv(nazivGrada);
grad.setId(idGradaElement);
gradoviLista.add(idGradaElement, nazivGradaElement);*/
}
a = nodeList.getLength();
//ovdje u varijablu zapisujem broj gradova, koje kasnije koristim samo za provjeru u main aktivitiju
The fetch from web service works, in variable a i store the length of elements, but the storing into variables does'nt work.
Element element = (Element) nodeList.item(i);
NodeList nazivGrada = element.getElementsByTagName("Naziv");
NodeList idGrada = element.getElementsByTagName("Id");
Element nazivGradaElement = (Element) nazivGrada.item(i);
Element idGradaElement = (Element) idGrada.item(i);
String gradNaziv = nazivGradaElement.getAttribute("Naziv");
This code does'nt work.
this is the xml: http://www.dajsve.com/rss.ashx?svigradovi=1
Can somebody help me?
nodeList.item(i); returns the node at the indexth position in the NodeList, a Node is not always an element so you will get a ClassCastException on:
Element element = (Element) nodeList.item(i);
Just make sure to check if(FPN.getNodeType() == Node.ELEMENT_NODE) before casting a Node to an Element
Or you can use:
Node node = nodeList.item(i);
String gradNaziv = getNodeValueByTagName(node ,"Naziv");

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();
}
}

how to read returned map values using key names outside a method - java

I am working on a selenium java script which would read data from an xml file. I have a read function which reads data from xml file and writes in to a map and that map data is returned.See below
public Map<String, String> read() throws ParserConfigurationException, IOException, SAXException {
Map<String, String> testData = new HashMap<String, String>();
File fXmlFile = new File("src/test/java/Blocks.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("blocks");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
NodeList childEls = eElement.getElementsByTagName("*");
for (int i = 0; i < childEls.getLength(); i++) {
Element cElement = (Element) childEls.item(i);
String name = cElement.getTagName();
String value = cElement.getTextContent();
value = System.getProperty("qa." + name, value);
testData.put(name, value);
}
}
System.out.println("array" + testData);
}
return testData;
}
Now i am not sure how to access values in the map outside read function - my xml file has url, username, password and 30+ rows of application data.
I can access values inside the read function but not sure how to do it outside the read function.
Any help would be appreciated. Thanks!

XML attribute Parsing

When parsing the xml, I want to retrieve the token value:
PCWTJ87OXNnGhwzvzqvbhepi2qQM6PhMdNHn7V9UuVw|
But I am currently getting the related:
Found attribute: expiry with value: 2014-10-29T22:20:00Z
xml file:
<?xml version="1.0"?>
<Inrix responseId="63448807-78d3-4ee8-90d6-a8b64abff8fc" statusText="" statusId="0" createdDate="2014-10-29T21:21:55Z" versionNumber="5.4" copyright="Copyright INRIX Inc." docType="GetSecurityToken">
<AuthResponse>
<AuthToken expiry="2014-10-29T22:20:00Z">PCWTJ87OXNnGhwzvzqvbhepi2qQM6PhMdNHn7V9UuVw|</AuthToken>
<ServerPath>devzone.inrix.com/traffic/inrix.ashx</ServerPath>
<ServerPaths>
<ServerPath region="NA" type="API">http://na.api.inrix.com/Traffic/Inrix.ashx</ServerPath>
<ServerPath region="NA" type="TTS">http://na-rseg-tts.inrix.com/RsegTiles/tile.ashx</ServerPath>
</ServerPaths>
</AuthResponse>
</Inrix>
This is the code I wrote to parse the xml file above:
DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
DocumentBuilder builder =factory.newDocumentBuilder();
Document document = builder.parse(new File(inputfile));
document.getDocumentElement().normalize();
NodeList AuthTokens = document.getElementsByTagName("AuthToken");
//NodeList AuthTokens = document.getElementsByTagName("ServerPath");
int num = AuthTokens.getLength();
for (int i=0; i<num;i++){
Element node = (Element) AuthTokens.item(i);
NamedNodeMap attributes = node.getAttributes();
int numAttrs = attributes.getLength();
for (int j=0; j<numAttrs;j++){
Attr attr = (Attr) attributes.item(j);
String attrName = attr.getNodeName();
String attrValue = attr.getNodeValue();
System.out.println(attr.getParentNode());
System.out.println("Found attribute: " + attrName + " with value: " + attrValue);
}
}
How do I get the correct value?
I believe you want the contents of the node, not its' attributes. Change your Element to Node and then you can call Node.getTextContent()
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File(inputfile));
document.getDocumentElement().normalize();
NodeList AuthTokens = document.getElementsByTagName("AuthToken");
// NodeList AuthTokens = document.getElementsByTagName("ServerPath");
int num = AuthTokens.getLength();
for (int i = 0; i < num; i++) {
Node node = AuthTokens.item(i);
String token = node.getTextContent();
System.out.println(token);
}
Output is (as requested)
PCWTJ87OXNnGhwzvzqvbhepi2qQM6PhMdNHn7V9UuVw|

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