I'm facing a problem with XML parsing with Java dom.
I have the following XML
<XXX>AA</XXX>
<YYY>BB</YYY>
<Params>
<Param>
<ParamID>10</ParamID>
<value>
<val1>1</val1>
<val2>2</val2>
<val3>3</val3>
</value>
</Param>
<Param>
<ParamID>20</ParamID>
<value>
<val1>4</val1>
<val2>5</val2>
<val3>6</val3>
</value>
</Param>
</Params>
I have this java code
String targetNodeName = "Params";
NodeList nodes = getParents(xmlString, targetNodeName);
for (int i = 0 ; i < nodes.getLength() ; i++){
Element currentElement = nodes.item(i);
NodeList fields = currentElement.getChildNodes();
for (int j = 0 ; j < fields.getLength() ; j++){
Node currentFieldElement = fields.item(j);
if (currentFieldElement != null && currentFieldElement.getNodeType() == Node.ELEMENT_NODE) {
String key = currentFieldElement.getNodeName();
String value = currentFieldElement.getTextContent();
Hashtable.put(key, value);
}
}
private static NodeList getParents (String xmlString, String tagName) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse( new InputSource( new StringReader( xmlString ) ) );
return document.getElementsByTagName(tagName);
}
The problem is that I want to have the result as a map (hashmap for example) with the pair
Example :
{ <XXX, [AA] > , <YYY, [BB] > , <10, [1 , 2 , 3] > ....}
How can I do this approach ?
Thank you
NodeList nodes = getParents(getTestingResponse(), targetNodeName);
HashMap<Integer, Object> hm = new HashMap<Integer, Object>();
for (int i = 0 ; i < nodes.getLength() ; i++){
Element currentElement = (Element) nodes.item(i);
NodeList fields = currentElement.getChildNodes();
for (int j = 0 ; j < fields.getLength() ; j++){
Node currentFieldElement = fields.item(j);
List<Integer> integer = new ArrayList<Integer>();
List<Integer> integerNew = new ArrayList<Integer>();
if (currentFieldElement != null && currentFieldElement.getNodeType() == Node.ELEMENT_NODE) {
String key = currentFieldElement.getNodeName();
String[] value = currentFieldElement.getTextContent().split("\n");
for (String v : value) {
System.out.println(v);
try {
integer.add(Integer.parseInt(v.trim()));
} catch(Exception e) {}
}
integerNew.add(integer.get(1));
integerNew.add(integer.get(2));
integerNew.add(integer.get(3));
hm.put(integer.get(0), integerNew);
}
}
}
System.out.println(hm);
Or otherwise, you can try this following code:
try
{
// File inputFile = new File("Input.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(DomParserPuCm.class.getResourceAsStream("Input.xml"));
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList params = doc.getElementsByTagName("Params");
HashMap<Integer, Object> paramsHM = new HashMap<Integer, Object>();
System.out.println(params.getLength());
for (int p = 0; p < params.getLength(); p++) {
NodeList param = params.item(p).getChildNodes();
if (param.item(p).getLocalName() != null) {
for (int z = 0; z < param.getLength(); z++) {
System.out.println(param.item(z).getLocalName());
if(param.item(z).getLocalName().equals("Param")) {
NodeList children = param.item(z).getChildNodes();
for (int c = 0; c < children.getLength(); c++) {
int paramID = 0;
int value1 = 0;
int value2 = 0;
int value3 = 0;
List<Integer> valueList = new ArrayList<Integer>();
if (children.item(c).getLocalName() != null) {
if (children.item(c).getLocalName().equals("ParamID")) {
try{paramID = Integer.parseInt(children.item(c).getFirstChild().getNodeValue());}catch(Exception e){}
} else if (children.item(c).getLocalName().equals("value")) {
NodeList values = children.item(c).getChildNodes();
try{value1 = Integer.parseInt(values.item(0).getFirstChild().getNodeValue());}catch(Exception e){}
try{value2 = Integer.parseInt(values.item(1).getFirstChild().getNodeValue());}catch(Exception e){}
try{value3 = Integer.parseInt(values.item(2).getFirstChild().getNodeValue());}catch(Exception e){}
valueList.add(value1);
valueList.add(value2);
valueList.add(value3);
}
}
System.out.print(valueList);
paramsHM.put(paramID, valueList);
}
}
}
}
}
System.out.print(paramsHM);
}
catch (Exception e)
{
e.printStackTrace();
}
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'm new to XML and I want to append points from an XML file to a point container that I wrote.
this is the XML file:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<container>
<point>
<X>56</X>
<Y>58</Y>
</point>
<point>
<X>59</X>
<Y>40</Y>
</point>
<point>
<X>70</X>
<Y>30</Y>
</point>
</container>
this is what I did:
private void OpenFile () throws ParserConfigurationException, SAXException, IOException {
JFileChooser of = new JFileChooser();
int option = of.showOpenDialog(of);
while (!of.getSelectedFile().getName().endsWith(".xml")) {
String error = "Error, Please select txt file";
JOptionPane.showMessageDialog(this, error, "Wrong type of file", JOptionPane.INFORMATION_MESSAGE);
of = new JFileChooser();
option = of.showOpenDialog(of);
}
if (option == JFileChooser.APPROVE_OPTION){
thisFile = new File(of.getSelectedFile().getPath());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(thisFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("container");
Element line = (Element) nList.item(0);
for(int i =0 ; i < nList.getLength() ; i++) {
Element point = (Element) line.getElementsByTagName("point").item(i);
x = Integer.parseInt(point.getElementsByTagName("X").item(0).getTextContent());
y = Integer.parseInt(point.getElementsByTagName("Y").item(0).getTextContent());
drewPoints(x, y);
pc.add(new Point(x, y));
}
}
my problem that it loop one time.
nList contains the list of container nodes, and you have only one such element in the XML document. You need to get the point elements instead:
NodeList nList = doc.getElementsByTagName("container");
Element containerElement = (Element) nList.item(0);
NodeList pointNodes = containerElement.getElementsByTagName("point");
for(int i = 0; i < pointNodes.getLength(); i++) {
Element point = (Element) pointNodes..item(i);
...
"my problem that it loop one time."
-- this is due to their being only one <container> node which is being iterated over:
NodeList nList = doc.getElementsByTagName("container"); // nList.getLength() == 1 here
Element line = (Element) nList.item(0);
for(int i =0 ; i < nList.getLength() ; i++) { // looping from i = 0 to i = 1
To make it iterate over all the points, do something like:
NodeList nList = doc.getElementsByTagName("container");
Element container = (Element) nList.item(0);
NodeList pointsList = container.getElementsByTagName("point");
for (int i = 0; i < pointsList.getLength(); i++) {
Element point = (Element) pointsList.item(i);
x = Integer.parseInt(point.getElementsByTagName("X").item(0).getTextContent());
y = Integer.parseInt(point.getElementsByTagName("Y").item(0).getTextContent());
drewPoints(x, y);
pc.add(new Point(x, y));
}
The issue in your code is that your are terminating the loop using nList.getLength() instead of line.getLength().
for(int i =0 ; i <line.getLength() ; i++) {
Your update code, this should work fine:
private void OpenFile () throws ParserConfigurationException, SAXException, IOException {
JFileChooser of = new JFileChooser();
int option = of.showOpenDialog(of);
while (!of.getSelectedFile().getName().endsWith(".xml")) {
String error = "Error, Please select txt file";
JOptionPane.showMessageDialog(this, error, "Wrong type of file", JOptionPane.INFORMATION_MESSAGE);
of = new JFileChooser();
option = of.showOpenDialog(of);
}
if (option == JFileChooser.APPROVE_OPTION){
thisFile = new File(of.getSelectedFile().getPath());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(thisFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("container");
Element line = (Element) nList.item(0);
for(int i =0 ; i < line.getLength() ; i++) {
Element point = (Element) line.getElementsByTagName("point").item(i);
x = Integer.parseInt(point.getElementsByTagName("X").item(0).getTextContent());
y = Integer.parseInt(point.getElementsByTagName("Y").item(0).getTextContent());
drewPoints(x, y);
pc.add(new Point(x, y));
}
}
}
<taxmann>
<docdetails>
<info id="104010000000007617" date="19780225">
<physicalpath>\\192.168.1.102\CMS\DATA</physicalpath>
<filepath isxml="N">
\NOTIFICATIONS\DIRECTTAXLAWS\HTMLFILES\150025021978.htm
</filepath>
<summary></summary>
<description></description>
<heading>
2187 [S.O.1500] | Section 35(1)(ii) of the Income-tax Act, 1961 - Scientific research expenditure - Approved scientific research associations/institutions
</heading>
<correspondingcitation/>
<hasfile>YES</hasfile>
<sortby>20120328160152743</sortby>
<parentid></parentid>
<parentchapterid></parentchapterid>
</info>
</docdetails>
</taxmann>
Code:
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_DOCDETAILS);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(KEY_HEADING, parser.getValue(e, KEY_HEADING));
// adding HashList to ArrayList
menuItems.add(map);
}
This is My Xml Format i want to xmlParse and want to dsiaply id,date,heading i m able to display heading But i am not to print date and id can u please tell me how i will implemnt it . this is my code to Print heading please modify my code and Print heading ,id,date..
1.Declaration
String URL = "http://www.google.co.in/ig/api?news&hl=en";
String KEY_ITEM = "news";
String KEY_ID = "news_entry";
String KEY_NAME = "title";
String KEY_COST = "url";
String KEY_DESC = "snippet";
2.Parsing
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
NamedNodeMap attributes = e.getAttributes();
System.out.println("attrlength"+attributes.getLength());
for (int a = 0; a < attributes.getLength(); a++)
{
Node theAttribute = attributes.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
NodeList nl1=e.getElementsByTagName(KEY_ID);
System.out.println("keyId"+nl1.getLength());
for(int j=0;j<nl1.getLength();j++)
{
Element e1 = (Element) nl1.item(j);
NodeList n = e1.getElementsByTagName(KEY_NAME);
for (int k = 0; k < n.getLength(); k++) {
Element e2 = (Element) n.item(k);
// System.out.println("node Title value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
Node theAttribute = attributes2.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
}
NodeList n1 = e1.getElementsByTagName(KEY_COST);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n1.getLength(); k++) {
Element e2 = (Element) n1.item(k);
// System.out.println("node Url value");
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
Node theAttribute = attributes2.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}}
NodeList n2 = e1.getElementsByTagName(KEY_DESC);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n2.getLength(); k++) {
Element e2 = (Element) n2.item(k);
// System.out.println("node snippet value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
Node theAttribute = attributes2.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
}
}
// menuItems.add(map);
}
NodeList nl = doc.getElementsByTagName("info");
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
NamedNodeMap attributes = e.getAttributes();
for (int a = 0; a < attributes.getLength(); a++)
{
Node theAttribute = attributes.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
}
I have the xml file as follows,
<CHPkt xmlns="Smartscript/EmarSchema">
<CHInfo>
<StoreId>1800</StoreId>
<CHId>DB439A79-3D6F-4D25-BE0A-C4692978C072</CHId>
<CHName>Test</CHName>
<Address>
<Address1>Test Address</Address1>
</Address>
<DrugRounds>
<RoundTime>09:00</RoundTime>
<RoundTime>13:00</RoundTime>
<RoundTime>17:00</RoundTime>
</DrugRounds>
</CHInfo>
</CHPkt>
How to get the values of the tags which has the same name, my code is as follows,
public class ReadXml {
public static void main(String[] args){
try{
File xmlFile = new File("/home/jayakumar/Desktop/SmartScript.XML");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlFile);
NodeList nodeList1 = document.getElementsByTagName("CHInfo");
System.out.println("######################################");
for(int i =0;i<nodeList1.getLength();i++){
org.w3c.dom.Node node = nodeList1.item(i);
if(node.getNodeType()== org.w3c.dom.Node.ELEMENT_NODE){
Element element = (Element) node;
System.out.println("StoreId : " + getTagValue("StoreId", element));
System.out.println("CHId : " + getTagValue("CHId", element));
System.out.println("CHName : " + getTagValue("CHName", element));
System.out.println("Address : " + getTagValue("Address1", element));
}
NodeList nodeList2 = document.getElementsByTagName("DrugRounds");
System.out.println("-------------->"+"DrugRounds");
for(int j =0;j<nodeList2.getLength();j++){
org.w3c.dom.Node subNode = nodeList2 .item(j);
Element e = (Element) subNode;
System.out.println("RoundTime : "+getTagValue("RoundTime", e));
System.out.println("RoundTime : "+getTagValue("RoundTime", e));
System.out.println("RoundTime : "+getTagValue("RoundTime", e));
}
}
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static String getTagValue(String sTag, Element element) {
NodeList nlList = element.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
}
I wasn't able to extract the values of second and third Roudtimes.How to parse the tags with same name
Thanks
Why not just check if it has any child nodes then get the value from it
for (int j = 0; j < nodeList2.getLength(); j++) {
org.w3c.dom.Node subNode = nodeList2.item(j);
NodeList childNodes = subNode.getChildNodes();
for(int iDx = 0; iDx < childNodes.getLength(); iDx++){
if(childNodes.item(iDx) instanceof Element){
Element e = (Element) childNodes.item(iDx);
System.out.println("RoundTime : "+ e.getFirstChild().getNodeValue());
}
}