How to go from one field to another in XML - java

<table name="categoryConfigTable">
<row>
<field name="mediaConfigId">0</field>
<field name="startDate">2005-01-01</field>
<field name="endDate">2025-12-31</field>
<field name="class">all</field>
<field name="CID">10</field>
<field name="sequenceNum">1</field>
<field name="parentCID">NULL</field>
</row>
</table>
This is part of my XML file, I want to retrieve CID values having parentCID as NULL
Part of my JAVA code is
`
public static void main(String[] args) {
try {
File fXmlFile = new File("/home/media.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nlist = doc.getElementsByTagName("field");
int len = nlist.getLength();
for (int i = 0; i < len; i++) {
Node node = nlist.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element e = (Element)node;
String attrVal = e.getAttribute("name");
try {
if(attrVal.equalsIgnoreCase("parentCID") && e.getTextContent().equals("NULL"))
{
System.out.println("root element" +e.getTextContent());
}
}
catch (IOException ie) {
//exception handling left as an exercise for the reader
}
}
}}catch (Exception e) {
e.printStackTrace();
}
}`
From this I get all parentCID having value as null but I want to go to CID how this can be done?

you can get it like this
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
File fXmlFile = new File("src/test.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :"
+ doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("row");
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 nList2 = eElement.getElementsByTagName("field");
String cidvalue=null;
for (int temp1 = 0; temp1 < nList2.getLength(); temp1++) {
Node nNode1 = nList2.item(temp1);
//System.out.println("\nCurrent Element Internal :"+ nNode1.getNodeName());
if (nNode1.getNodeType() == Node.ELEMENT_NODE) {
Element eElement1 = (Element) nNode1;
if(eElement1.getAttribute("name").equalsIgnoreCase("CID"))
{
cidvalue=eElement1.getTextContent();
}
if(eElement1.getAttribute("name").equalsIgnoreCase("parentCID") && (eElement1.getTextContent().equalsIgnoreCase("NULL")))
{
// System.out.println(eElement1.getTextContent());
System.out.println("row["+temp+"] where parentCID is NULL and corresponding CID value :: "+cidvalue);
cidvalue=null;
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Related

Store xml value as a Map using XPATH using JAVA

I am using XPATH to parse xml document,please find the xml below
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<bookEvent>
<bookName>harry_potter</bookName>
<bookEntity>comic</bookEntity>
<bookEntityId>10987645</bookEntityId>
<bookParameter>
<name>Name1</name>
<value>value1</value>
</bookParameter>
<bookParameter>
<name>Name2</name>
<value>value2</value>
</bookParameter>
<bookParameter>
<name>Name3</name>
<value>value3</value>
</bookParameter>
<bookParameter>
<name>Name4</name>
<value>value4</value>
</bookParameter>
<bookParameter>
<name>Name5</name>
<value>value5</value>
</bookParameter>
</bookEvent>
</soap:Body>
</soap:Envelope>
Here I would like to convert BookParameters to Map like below
{"Name1":"value1","Name2":"value2" etc}
I have tried the below code and i can get a Map but not in the expected format,
try{
Map<String,String> eventParameters = new HashMap<>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("book.xml");
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
NodeList nodeList = (NodeList)xpath.compile("//bookEvent//eventParameter").evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if(node.hasChildNodes()) {
NodeList childNodes = node.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Node childNode = childNodes.item(j);
if (childNode.getNodeType() == Node.ELEMENT_NODE) {
System.out.println(childNode.getNodeName()+"::"+childNode.getNodeValue()+"::"+childNode.getTextContent());
eventParameters.put(childNode.getTextContent(),childNode.getTextContent());
}
}
}
}
System.out.println("print map::"+eventParameters);
} catch (Exception e) {
e.printStackTrace();
}
The output looks like this
print map::{Name3=Name3, Name4=Name4, value5=value5, Name5=Name5, value2=value2, value1=value1, value4=value4, value3=value3, Name1=Name1, Name2=Name2}
Please somebody guide me to create a below map from the xml,Any help would be appreciable.
{"Name1":"value1","Name2":"value2" etc}
You can do it as a one-liner in XPath 3.1:
map:merge(//bookParameter!map{string(name): string(value)})
=> serialize(map{'method':'json'})
You can run XPath 3.1 from Java by installing Saxon-HE 9.8 (open source)
Use Below code :
import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ReadXMLFile {
public static Map<String,String> hMap = new LinkedHashMap<>();
public static void main(String argv[]) {
try {
File fXmlFile = new File("C:\\Users\\jaikant\\Desktop\\QUESTION.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("bookParameter");
for (int parameter = 0; parameter < nodeList.getLength(); parameter++) {
Node node = nodeList.item(parameter);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) node;
String name = eElement.getElementsByTagName("name").item(0).getTextContent();
String value = eElement.getElementsByTagName("value").item(0).getTextContent();
hMap.put(name, value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
hMap.forEach((h,k) -> {
System.out.println(h + ":" + k);
});
}
}
It will print exactly what you are looking for.

Java - Delete child node from dynamic XML

I want to delete a XML node that contains a PDF in Base64. This is an example:
<?xml version="1.0" encoding="UTF-8"?>
<getResult>
<id>null</id>
<pdf>ioje98fh23fjkiwf72322342</pdf>
</getResult>
First, I transform the XML in String to Document but the result is null. This is my code:
DocumentBuilder dbf = null;
Document doc = null;
try {
dbf = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<getResult><id>null</id><pdf>ioje98fh23fjkiwf72322342</pdf></getResult>"));
doc = dbf.parse(is);
NodeList children = doc. getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node currentChild = children.item(i);
System.out.println(currentChild);
}
} catch (Exception e) {
System.out.println(e.getMessage().toString());
}
The result is always: [getResult: null]
Considering that the main node can vary but the structure does not, How can I get the PDF node?
Here is the could you could use to retrieve the data.
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.w3c.dom.CharacterData;
public class LabFour {
public static void main(String[] args) {
DocumentBuilder dbf = null;
Document doc = null;
try {
dbf = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(
new StringReader("<getResult><id>null</id><pdf>ioje98fh23fjkiwf72322342</pdf></getResult>"));
doc = dbf.parse(is);
NodeList nodes = doc.getElementsByTagName("getResult");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("id");
Element line = (Element) name.item(0);
System.out.println("id: " + getCharacterDataFromElement(line));
NodeList pdf = element.getElementsByTagName("pdf");
line = (Element) title.item(0);
System.out.println("pdf: " + getCharacterDataFromElement(pdf));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}
}
SimpleXml can do it:
final SimpleXml simple = new SimpleXml();
final Element element = simple.fromXml(data);
element.children.remove(1);
System.out.println(simple.domToXml(element));
Will output:
<getResult><id>null</id></getResult>
From maven central:
<dependency>
<groupId>com.github.codemonstur</groupId>
<artifactId>simplexml</artifactId>
<version>1.4.0</version>
</dependency>

Modifying value of a particular tag in xml

I have an xml as follows
<?xml version="1.0" encoding="ISO-8859-1"?><TXNEXP FileDate="2017-05-23" FileName="/cortex/tsd/out/OPTSKRtxnexp20170523.xml" Instcode="SKR" TotNumTxns="74330">
<AUTHADV>
<LOCALDATE>2017-05-22</LOCALDATE>
<LOCALTIME>200011</LOCALTIME>
<PAN>336890380<PAN>
</AUTHADV>
<AUTHREV>
<LOCALDATE>2017-05-22</LOCALDATE>
<LOCALTIME>200011</LOCALTIME>
<PAN>336890380<PAN>
</AUTHREV>
<FINAL>
<LOCALDATE>2017-05-22</LOCALDATE>
<LOCALTIME>200011</LOCALTIME>
<PAN>336890380<PAN>
</FINAL>
</TXNEXP>
Now, I am modifying the value of PAN tag and writing it back to the xml but I am not able to do so for all the PAN tags.
Here is what I am doing.
NodeList node = doc.getElementsByTagName("TXNEXP");
Element emp = null;
for (int i = 0; i < node.getLength(); i++) {
emp = (Element) node.item(i);
Node name = emp.getElementsByTagName("PAN").item(0).getFirstChild();
//Modifying the tag
}
From the above code only PAN under AUTHADV tag gets modified and the rest two values don't change.
How can I ensure all the PAN tags to get modified ?
This is not the prettiest solution but after you fix the missing slash in the PAN closing tags this will work.
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
class Extract {
public static void main(String[] args) {
try {
File fXmlFile = new File("data.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
NodeList topNodes = doc.getElementsByTagName("TXNEXP");
for (int i = 0; i < topNodes.getLength(); i++) {
NodeList middleNodes = topNodes.item(i).getChildNodes();
for (int j = 0; j < middleNodes.getLength(); j++) {
try {
NodeList theNodes = ((Element)middleNodes.item(j)).getElementsByTagName("PAN");
System.out.println(theNodes.item(0).getFirstChild().getNodeValue());
if (j == 1) {
// modify a value
theNodes.item(0).getFirstChild().setNodeValue("4567");
System.out.println(theNodes.item(0).getFirstChild().getNodeValue());
}
} catch (ClassCastException e) {}
}
}
} catch (Exception e) {
System.out.println(e);
}
}
}
For a slightly better approach you could use XPaths.
import javax.xml.xpath.*;
class Extract {
public static void main(String[] args) {
try {
File fXmlFile = new File("data.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList)xpath.evaluate("/TXNEXP/*/PAN", doc, XPathConstants.NODESET);
for (int n = 0; n < nodes.getLength(); n++) {
System.out.println(nodes.item(n).getFirstChild().getNodeValue());
if (n == 1) {
nodes.item(n).getFirstChild().setNodeValue("4567");
System.out.println(nodes.item(n).getFirstChild().getNodeValue());
}
}
} catch (Exception e) {
System.out.println(e);
}
}
}

how to read a kml file on java

If I switch it to xml it works fine but to kml nothing. thought it was basically the same thing,probably missing something silly, or messed it up completly sorry for inconvience but help is much appreciated. basically just trying to read a kml file data on java.
package mysqlcon;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
File fXmlFile = new File("C:/Users/D/Desktop/mysql/mappedv.kml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("mappedv");
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;
System.out.println("coordinates : " + eElement.getElementsByTagName("coordinates").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Method getTagValue() is undefined in JAVA

I'm new to Java. I saw many example about reading XML and when I tried to copy to my code I got an error that getTagValue is undefined.
I'm using Eclipse, JRE 1.6.
As well as I understand that method (getTagValue) is exist?
This is the errors:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method getTagValue(String, Element) is undefined for the type WriteXMLFile
The method getTagValue(String, Element) is undefined for the type WriteXMLFile
The method getTagValue(String, Element) is undefined for the type WriteXMLFile
The method getTagValue(String, Element) is undefined for the type WriteXMLFile
this the code:
import java.io.File;
import java.io.ObjectInputStream.GetField;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
public class WriteXMLFile
{
public static void main(String argv[])
{
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("company");
doc.appendChild(rootElement);
// staff elements
Element staff = doc.createElement("Staff");
rootElement.appendChild(staff);
// set attribute to staff element
Attr attr = doc.createAttribute("id");
attr.setValue("1");
staff.setAttributeNode(attr);
// shorten way
// staff.setAttribute("id", "1");
// firstname elements
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode("yong"));
staff.appendChild(firstname);
// lastname elements
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode("mook kim"));
staff.appendChild(lastname);
// nickname elements
Element nickname = doc.createElement("nickname");
nickname.appendChild(doc.createTextNode("mkyong"));
staff.appendChild(nickname);
// salary elements
Element salary = doc.createElement("salary");
salary.appendChild(doc.createTextNode("100000"));
staff.appendChild(salary);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("file.xml"));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
System.out.println("File saved!");
}
catch (ParserConfigurationException pce)
{
pce.printStackTrace();
}
catch (TransformerException tfe)
{
tfe.printStackTrace();
}
///// read
try {
File fXmlFile = new File("c:\\file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("staff");
System.out.println("-----------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("First Name : " + getTagValue("firstname", eElement));
System.out.println("Last Name : " + getTagValue("lastname", eElement));
System.out.println("Nick Name : " + getTagValue("nickname", eElement));
System.out.println("Salary : " + getTagValue("salary", eElement));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This method needs to be included in your class file somewhere
private String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
.getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}

Categories

Resources