Casting node to element giving ClassCastException - java

here n2 is my NodeList, and i just want to see the first child node of my root element
public void ClickMe(View view){
Node rootElement=n2.item(0);
NodeList child=rootElement.getChildNodes();
Node first=child.item(0);
//ClassCastException error is coming whenever i am casting first to Element.
Element nm=(Element)first;
Option q= getOption(nm,first);
Log.i(TAG,"the name is was talking about is : "+ q.getName());
}
this what logcat says
07-31 20:32:38.376: E/AndroidRuntime(2950): Caused by: java.lang.ClassCastException: org.apache.harmony.xml.dom.TextImpl cannot be cast to org.w3c.dom.Element

Try it like this....
NodeList LOP = odoc.getElementsByTagName("Your_XML_Top_Element");
Node FPN =LOP.item(0);
try{
if(FPN.getNodeType() == Node.ELEMENT_NODE)
{
Element token = (Element)FPN;
NodeList oNameList1 = token.getElementsByTagName("Your_XML_Sub_Node");
Element firstNameElement = (Element)oNameList1.item(0);
NodeList textNList1 = firstNameElement.getChildNodes();
}

If node is element then only cast it. Make check like below.
if (first.getNodeType() == Node.ELEMENT_NODE) { Element nm=(Element)first;}

Related

xml update value using dom in java

I have to change the value that I find in the eElement that matches with the old value with another one.
I try with eElement.setAttribute(...) function and with setTextContent function but it doesn't work.
If we suppose that the new value is stored in a String variable called newValue, how can I make my code run?
NodeList leaf = doc.getElementsByTagName(relativeLeaf);
System.out.println(leaf.item(0).getNodeName());
for (int temp = 0; temp < leaf.getLength(); temp++) {
Node nNode = leaf.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String oldValueInCells = eElement.getElementsByTagName(relativeLeaf).item(0).getTextContent();
System.out.println("old tag : " + eElement.getElementsByTagName(relativeLeaf).item(0).getTextContent());
if(oldValueInCells.contentEquals(oldVal)){
// ####
// here i have to change tha value in eElement
// where it match with the old Value with a new one
}
}
}
Basing on the documentation I think you can get the Node Element and then set a value. You first should get the node element like this:
Node node = eElement.getElementsByTagName(relativeLeaf).item(0); //You get the node here so you can use it as well to create OldValueInCells
String oldValueInCells = node.getTextContent();
System.out.println("old tag : " + oldValueInCells);
if(oldValueInCells.contentEquals(oldVal)){
// ####
// here i have to change tha value in eElement
// where it match with the old Value with a new one
node.setTextContent("new value"); //Here you will set the value to the node
}
Source: https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Node.html

how remove XML Node with java

i need to remove the "Object" tag, but I need to preserve and keep the content. Is that possible?
<ds:KeyInfo>
<wsse:SecurityTokenReference>
<wsse:Reference URI="#b3f74c53-b79f-4dec-aa26-ca552f8f8745"/>
</wsse:SecurityTokenReference>
</ds:KeyInfo>
<ds:Object Id="id1"> // <-Remove this
<wsu:Timestamp>
<wsu:Created>2017-03-28T20:21:44Z</wsu:Created>
<wsu:Expires>2017-03-28T23:08:24Z</wsu:Expires>
</wsu:Timestamp>
</ds:Object> // <-Remove this
I tried:
Node node = xml.getElementById("id1");
xml.getDocumentElement().removeChild(node);
but:
Org.w3c.dom.DOMException: NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist.
First of all, only the parent of the node to be removed can remove it:
Node nodeToBeRemoved = xmlDoc.getElementById("id1");
Node parentNode = nodeToBeRemoved.getParentNode();
Node removedNode = parentNode.removeChild(nodeToBeRemoved);
Second, in order to "preserve and keep the content" you will need to attach the children elements of the removed one to its parent:
NodeList removedChildren = removedNode.getChildNodes();
for (int i = 0 ; i < removedChildren.getLength(); i++) {
Node child = removedChildren.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
parentNode.appendChild(child);
}
}

Couldn't able to read the attribute using DOM parser

i am having issues when reading the attribute of a link,
this is the structure of my xml,
<entry>
<updated>
<title>
<link href="">
</entry>
i managed to read the date and title correctly but the href attribute of the link is not working.
Here is my code,
NodeList nList = doc.getElementsByTagName("entry");
System.out.println("============================");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node node = nList.item(temp);
System.out.println(""); //Just a separator
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) node;
System.out.println("Date : " + eElement.getElementsByTagName("updated").item(0).getTextContent());
System.out.println("Title : " + eElement.getElementsByTagName("title").item(0).getTextContent());
// The below code is for reading href attribute of link,
NodeList node1 = eElement.getElementsByTagName("link");
Element eElement1 = (Element) node1;
System.out.println(eElement1.getAttribute("href"));
}
}
I am creating a new nodelist for the attributes of link but the code is not working.
error:
java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeepNodeListImpl cannot be cast to org.w3c.dom.Element
at Demo.main(Demo.java:45)
A NodeList is not an Element and cannot be cast to one (successfully), so this code isn't going to work:
NodeList node1 = eElement.getElementsByTagName("link");
Element eElement1 = (Element) node1;
A NodeList is, as the name suggests, a list of nodes (and in your case, the nodes will be Elements). So this code would work for the first link:
NodeList list = eElement.getElementsByTagName("link");
Element eElement1 = (Element) list.item(0);
...whereupon your getAttribute should work fine, as Element has getAttribute.
Side note: If your library has support for newer query functions, you could also do this:
String href = ((Element)eElement.querySelector("entry")).getAttribute("href");
...because querySelector returns just the first match (not a list) (or null if no matches; if that's a possibility, add a guard to the above). But I don't know how well querySelector is supported outside of browsers yet.
// The below code is for reading href attribute of link,
NodeList node1 = eElement.getElementsByTagName("link");
Element eElement1 = (Element) node1;
NodeList will give you Node object not Element, you can get href value as follows,
String hrefValue = nodeList.item(0).
getAttributes().getNamedItem("href").getNodeValue();

Retrieve node element's value based on attribute

How to retrieve node element's value based on attribute name using dom & xml parsing
<ROOT>
<A>
<aa name="xyz">k,l,m </aa>
<aa name="pqr">a,b,h </aa>
<aa name="abc">s,t,r </aa>
...
</A>
<B>
<bb name="t1">r,st,t</bb>
...
</B>
</ROOT>
...
Fragment of implementation tried:
NodeList nodeList = <xmlDoc>.getElementsByTagName("aa");
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) node;
System.out.println(element.getTextContent());
// ? getNodeValue() // ? how to get by passing attribute name as matching criteria,
// f.e : how to get a,b,h printed for node aa with attribute name as pqr
For attribute it will be : element.getAttribute("name");
If you want to search by attribute, then
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nl = (NodeList)xpath.compile("//aa[#name='pqr']").evaluate(doc, XPathConstants.NODESET);
//Rest of the code same
*Please change the xpath according to your need. I did not run it myself, but you get the idea.

java.lang.ClassCastException, DeepNodeListImpl cannot be cast

here is my code :
public void Login() {
try{
DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = builderfactory.newDocumentBuilder();
File path = new File("src/dataPengguna/dataPengguna.xml");
Document doc = db.parse(path);
Element pengguna = (Element) doc.getElementsByTagName("pengguna");
NodeList list = pengguna.getElementsByTagName("user");
for (int i = 0; i < list.getLength(); i++) {
Element user = (Element) list.item(i);
Node username = user.getElementsByTagName("username").item(i);
Node password = user.getElementsByTagName("password").item(i);
if(loginuser.getText().equals(username.getTextContent())
&& loginpass.getText().equals(password.getTextContent())){
JOptionPane.showMessageDialog(rootPane, "welcome");
}
}
}catch(Exception e){
e.printStackTrace();
}
}
here is my xml :
<?xml version="1.0" encoding="UTF-8"?>
<pengguna>
<user>
<nama>septian</nama>
<username>septiansykes</username>
<password>1234</password>
<status>belumpinjam</status>
</user>
<user>
<nama>koko</nama>
<username>kokosan</username>
<password>12er</password>
<status>belumpinjam</status>
</user>
<user>
<nama>tamrin</nama>
<username>tamrincs</username>
<password>gt234</password>
<status>belumpinjam</status>
</user>
</pengguna>
and here is my error :
java.lang.ClassCastException:com.sun.org.apache.xerces.internal.dom.DeepNodeListImpl cannot be cast to org.w3c.dom.Element
i try to get the element at the xml file, i want to check the element username and password, but there is an error about the cast class, it's seem difficult for me,... thanks before
This is the problem:
Element pengguna = (Element) doc.getElementsByTagName("pengguna");
getElementsByTagName doesn't return a single element - it returns multiple elements. You probably want something like:
NodeList penggunas = doc.getElementsByTagName("pengguna");
if (penggunas.getLength() != 1) {
// Handle this - e.g. throw an exception
}
Element pengguna = (Element) penggunas.item(0);
EDIT: Later, you've got a bug here:
Node username = user.getElementsByTagName("username").item(i);
Node password = user.getElementsByTagName("password").item(i);
This should be:
Node username = user.getElementsByTagName("username").item(0);
Node password = user.getElementsByTagName("password").item(0);
You're already within the user element - so you always want the first username and password elements within that element. Otherwise you're asking for the second username element within the second user element, the third username element within the third user element etc. The numbering is relevant to the element that you're in, not some global count.
getElementByTagName() returns a NodeList and you try to cast it to an Element. This line is incorrect and will give you the ClassCastException:
Element pengguna = (Element) doc.getElementsByTagName("pengguna");

Categories

Resources