xml update value using dom in java - 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

Related

Dom parsing xml problems

I have a simple .xml file and need to parse it. The file is the following:
<table name="agents">
<row name="agent" password="pass" login="agent" ext_uid="133"/>
</table>
I need to get values of name, password, login, ext_uid to create a DB record.
What I have done for this:
created an or.w3c.dom.Document:
public Document getDocument(String fileName){
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
f.setValidating(false);
DocumentBuilder builder = f.newDocumentBuilder();
return builder.parse(new File(fileName));
}
next I'm trying to print values:
document = getDocument(fileName);
NodeList nodes = document.getChildNodes();
for (int i=0; i<nodes.getLength(); i++){
Node node = nodes.item(i);
if(node.getNodeType() == Node.ELEMENT_NODE){
NodeList listofNodes = node.getChildNodes();
for(int j=0; j<listofNodes.getLength(); j++){
if(node.getNodeType() == Node.ELEMENT_NODE){
Node childNode = listofNodes.item(j);
System.out.println(childNode.getNodeValue()+" " + childNode.getNodeName());
}
}
}
}
I use this because I'm trying to find out how to get values: childNode.getNodeValue()+" " + childNode.getNodeName()
but the result is the following:
#text
null row
#text
in the first and te third cases the NodeValue is empty and in the second case it is null, that means, I guess that there no NodeValue at all.
So my question is how to get values of name, password, login, ext_uid?
childNode.getNodeValue() is obviously null as its an empty tag. You have to look for attributes
Node childNode = listofNodes.item(j);
Element e = (Element)childNode;
String name = e.getAttribute("name");
String password= e.getAttribute("password");
String login= e.getAttribute("login");
String ext_uid= e.getAttribute("ext_uid");
The <row> element has no value, it only has attributes. If it had a value it would look more like <row>this would be the value returned from getNodeValue()</row>.
One way to get the data is to iterate the XML node attributes, for example:
NamedNodeMap attrs = childNode.getAttributes();
if (attrs != null) {
for (int k = 0; k < attrs.getLength(); k++) {
System.out.println("Attribute: "
+ attrs.item(k).getNodeName() + " = "
+ attrs.item(k).getNodeValue());
}
}
The output of your code is showing #text due to the carriage returns (\n characters) in the example XML file, which, according the specification, should be preserved. The null in the example output is the empty node value from the value-less <row> element.
Use XPath instead:
XPath xp = XPathFactory.newInstance().newXPath();
System.out.println(xp.evaluate("/table/row/#name", doc));
System.out.println(xp.evaluate("/table/row/#password", doc));
System.out.println(xp.evaluate("/table/row/#login", doc));
System.out.println(xp.evaluate("/table/row/#ext_uid", doc));

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

java Convert Element to string

I am looking to get only the tag name, and not it's children.
I have an xml like this:
<RESPONSE>
<RESULT> !--TableName
<ADDRESS1>123 Main Street</ADDRESS1> !--ColumnName
<ZIP>12345</ZIP> !--ColumnName
</RESULT>
<RESULT> !--TableName
<ADDRESS1>245 Elm Street</ADDRESS1> !--ColumnName
<ZIP>45678</ZIP> !--ColumnName
</RESULT>
<VIN> !--TableName
<VIN_NUM>1K45678RTW23</VIN> !--ColumnName
</VIN>
….
</REPSONSE>
I am trying to dynamically save the xml into it's appropriate table and column names. So, I want to extract whatever the first element is, and assign it to a table name variable, and then it's children as columns.
Here is what I am doing so far:
private void extractToTableSet(Document doc, int appseqno ) throws Exception
{
NodeList responseList = doc.getElementsByTagName("RESPONSE");
for (int i = 0; i < responseList.getLength(); i++) {
Node currentNode = responseList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
Element tableElement = (Element) responseList.item(i);
if (tableElement != null && tableElement.hasChildNodes()) {
for (columnNode = tableElement.getFirstChild(); columnNode != null; columnNode = columnNode.getNextSibling()) {
if (columnNode.getNodeType() == Node.TEXT_NODE) {
columnName = columnNode.getNodeValue;
}
}
}
}
}
}
This way I am only able to get the values in the child nodes. Is there a way to get the name of the Element tags? Like I want to extract the value RESULT from the Document object.
In DOM, an element name is retrieved using Node.getNodeName().
Example:
if(node.getNodeType() == Node.ELEMENT_NODE) {
String elementName = node.getNodeName();
...
}
To get element's tagname :
Element tableElement = (Element) responseList.item(i);
String tagname = tableElement .getTagName();

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");

Casting node to element giving ClassCastException

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

Categories

Resources