Equivalent of "For XML" in MS Access SQL - java

I need to select records from an MS Access database to an XML output, based on some predefined conditions, from my Java application using JDBC & SQL statements.
Is there a way to achieve that?

Access SQL does not have an equivalent to T-SQL's FOR XML clause. However, you can add a class like this to your project
package com.example.ucanaccessdemo;
import java.io.StringWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
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.Document;
import org.w3c.dom.Element;
public class ResultSetToXml {
// adapted from
// http://www.java2s.com/Code/Java/Database-SQL-JDBC/ConvertaResultSettoXML.htm
public static String asXml(ResultSet rs) throws ParserConfigurationException, SQLException, TransformerException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element results = doc.createElement("Results");
doc.appendChild(results);
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
while (rs.next()) {
Element row = doc.createElement("Row");
results.appendChild(row);
for (int i = 1; i <= colCount; i++) {
String columnName = rsmd.getColumnName(i);
Object value = rs.getObject(i);
if (value != null) {
Element node = doc.createElement(columnName);
node.appendChild(doc.createTextNode(value.toString()));
row.appendChild(node);
}
}
}
DOMSource domSource = new DOMSource(doc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
StringWriter sw = new StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);
return sw.toString();
}
}
and then pass your ResultSet to the asXml method
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Clients");
String xml = ResultSetToXml.asXml(rs);
For a sample table like this ...
ID LastName FirstName DOB
-- ------------ --------- -------------------
1 Thompson Gord 2017-04-01 07:06:27
2 Loblaw Bob 1966-09-12 16:03:00
3 Παπαδόπουλος Ώπα
... the resulting xml string will look like this (formatted for readability)
<Results>
<Row>
<ID>1</ID>
<LastName>Thompson</LastName>
<FirstName>Gord</FirstName>
<DOB>2017-04-01 07:06:27.0</DOB>
</Row>
<Row>
<ID>2</ID>
<LastName>Loblaw</LastName>
<FirstName>Bob</FirstName>
<DOB>1966-09-12 16:03:00.0</DOB>
</Row>
<Row>
<ID>3</ID>
<LastName>Παπαδόπουλος</LastName>
<FirstName>Ώπα</FirstName>
</Row>
</Results>

Related

How can I replace an attribute in xml with different value using Java?

I have an xml file:
<pickingOrderBeginEventMessage xmlns="http://www.xmlns.walmartstores.com/SuppyChain/FulfillmentManagement/GlobalIntegeratedFulfillment/">
<MessageBody>
<RoutingInfo>
<SourceNode>
<location>
<countryCode>US</countryCode>
</location>
</SourceNode>
</RoutingInfo>
<fulfillmentOrders>
<fulfillmentOrder>
<orderNbr>784</orderNbr>
</fulfillmentOrder>
</fulfillmentOrders>
</MessageBody>
</pickingOrderBeginEventMessage>
I want to change <orderNbr>784</orderNbr> to <orderNbr>784778474484747</orderNbr>
This is my method:
(Note that I am using dom4j.)
public String replaceXML(String attribute,String oldValue, String newValue) throws SAXException, DocumentException, IOException, TransformerException {
SAXReader xmlReader = new SAXReader();
Document input = xmlReader.read("src/test/resources/xml/pick_begin.xml");
xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
xmlReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
String expr = String.format("//*[contains(#%s, '%s')]", attribute, oldValue);
XPath xpath = DocumentHelper.createXPath(expr);
List<Node> nodes = xpath.selectNodes(input);
for (int i = 0; i < nodes.size(); i++) {
Element element = (Element) nodes.get(i);
element.addAttribute(attribute, newValue);
}
TransformerFactory factory = TransformerFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer xformer = factory.newTransformer();
xformer.setOutputProperty(OutputKeys.INDENT, "yes");
Writer output = new StringWriter();
xformer.transform(new DocumentSource(input), new StreamResult(output));
return output.toString();
}
}
Where String attribute is orderNbr, oldValue is 784 and newValue is 78455556767.
But with this method, the new value is not getting replaced. Where am I going wrong?
According to the XML file in your question, orderNbr is an element and not an attribute and its text value is 784. So you want to replace the text value with 78455556767.
Your code does not change the original XML because your XPath query string does not find anything.
Therefore you need to change two things in your code.
The XPath query string.
The method you call to change the XML.
The below code contains the two changes. The changed lines are indicated with the following comment at the end of the line.
// CHANGE HERE
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.List;
import javax.xml.XMLConstants;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.XPath;
import org.dom4j.io.DocumentSource;
import org.dom4j.io.SAXReader;
import org.xml.sax.SAXException;
public class ChngAttr {
public static String replaceXML(String attribute,
String oldValue,
String newValue) throws DocumentException,
IOException,
SAXException,
TransformerException {
SAXReader xmlReader = new SAXReader();
Document input = xmlReader.read("pick_begin.xml");
xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
xmlReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
String expr = String.format("//%s[text() = '%s']", attribute, oldValue); // CHANGE HERE
XPath xpath = DocumentHelper.createXPath(expr);
List<Node> nodes = xpath.selectNodes(input);
for (int i = 0; i < nodes.size(); i++) {
Element element = (Element) nodes.get(i);
element.setText(newValue); // CHANGE HERE
}
TransformerFactory factory = TransformerFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer xformer = factory.newTransformer();
xformer.setOutputProperty(OutputKeys.INDENT, "yes");
Writer output = new StringWriter();
xformer.transform(new DocumentSource(input), new StreamResult(output));
return output.toString();
}
public static void main(String[] args) throws Exception {
String result = replaceXML("orderNbr", "784", "78455556767");
System.out.println(result);
}
}

How to modify an xml document and return it as a string in java?

I have this string containing my request xml. I want to delete below "id" tags from this string if they exist and return it back. Removing "Identity" completely will also work, if that can be done.
To be deleted :
<Identity>
<id extension="7865232" aan = "BUH"/>
<code/>
</Identity>
<Identity>
<id extension="88769032" aan = "DIH"/>
<code/>
</Identity>
String XMLString= "<request version ="1.0">
<minMatch>
<val>100</val>
</minMatch>
<paramList>
<payLoad display = "Full" type="F">
</payLoad>
<IQC code = "2">
</IQC>
<Control display="Default" type = "D">
</Control>
<member>
<memCode code = "Active"
</memCode>
<id extension="12345" aan="ACC"></id>
<id extension="54321" aan="REQ"></id>
<id extension="554376" aan="PDR"></id>
<id extension="66321" aan="NJQ"></id>
<addr use = "H">
<streetLine>123</streetLine>
<city>POLIS</city>
<state>NY</state>
<postalCode>44321</postalCode>
</addr>
<telecom value = "5543213">
</telecom>
<Person>
<name>
<given>JOHN</given>
<family>BILL</family>
</name>
<GenderCode code ="M" display="Male">
</GenderCode>
<birthime vaue="19651002">
</birthime>
<Identity>
<id extensio="7865232" aan = "BUH"/>
<code/>
</Identity>
<Identity>
<id extensio="88769032" aan = "DIH"/>
<code/>
</Identity>
</Person>
</member>
----
---
</request>"
I am using below code to achieve the same but it's not working and giving me The constructor DOMSource(Document) is undefined. I tired converting document into a byte Array but that's also not working.Is there any way i can simply do this in Java 1.8. Any other approach is also welcome.
Please suggest.Thank you!
public void removeIds(String xmlString){
Document doc = null;
SAXBuilder saxbuilder = new SAXBuilder();
try{
doc = saxbuilder.build(new StringReader(xmlString));
}catch(JDOMException je){
je.printStackTrace();
}catch(IOException ie){
ie.printStackTrace();
}
Element rootNode = doc.getRootElement();
IteratorIterable<Element> rootChildren=rootNode.getDescendants(new ElementFilter("Person"));
for(Element Person:rootChildren){
for(Element Identity:Person.getChildren("Identity")){
((Element) doc.getRootElement.getDescendants(new ElementFilter("Identity"))).removeChild("id");
}
}
try{
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer;
transformer = tf.newTransformer();
// transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString();
return output;
} catch (TransformerException e) {
e.printStackTrace();
}
}
Since you're invoking a transformation anyway, it's much simpler to do all the work in XSLT rather than fiddle about with low-level DOM manipulation.
If you use XSLT 3.0 (Saxon) then the stylesheet is simply
<xsl:transform version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:mode on-no-match="shallow-copy"/>
<xsl:output indent="yes" encoding="utf-8"/>
<xsl:template match="id"/>
</xsl:transform>
You can supply the input to this transformation as new StreamSource(new StringReader(xmlString)) -- there's no need to construct a DOM first.
It can be done in XSLT 1.0 too (i.e. with Xalan, which comes bundled with the JDK), but is a bit more verbose.
Here is solution using XPath API. In this example all elements "id" inside elements "Identity" are removed (XPath expression "//Identity/id"). If you want to remove all id elements, change it to "//id".
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
// function for XML serialization
public static String serialize(Document document) {
removeWhitespaces(document.getDocumentElement());
try (StringWriter writer = new StringWriter()) {
StreamResult result = new StreamResult(writer);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(new DOMSource(document), result);
return writer.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// helper function for stripping whitespaces
public static void removeWhitespaces(Element element) {
NodeList children = element.getChildNodes();
for (int i = children.getLength() - 1; i >= 0; i--) {
Node child = children.item(i);
if (child instanceof Text
&& ((Text) child).getData().trim().isEmpty()) {
element.removeChild(child);
} else if (child instanceof Element) {
removeWhitespaces((Element) child);
}
}
}
Main code:
// parse XML
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xml)));
// find id elements
XPathExpression xpath = XPathFactory.newInstance().newXPath().compile("//Identity/id");
NodeList nodes = (NodeList)xpath.evaluate(doc, XPathConstants.NODESET);
// remove found elements
for(int i = 0; i < nodes.getLength(); i ++) {
Node node = nodes.item(i);
node.getParentNode().removeChild(node);
}
// serialize and output document
String result = serialize(doc);
System.out.println(result);

How to insert a new XML node within an existing Node using Java

I am trying to insert a new node within an exsting node for N number of times, however it is not working for me, following is what I am doing:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filePath);
Node pNode = doc.getElementsByTagName(parentNode).item(0);
for (int i = 1; i <= count; i++) {
String nodeValue = value;
Element newNode = doc.createElement(childNode);
newNode.appendChild(doc.createTextNode(nodeValue));
pNode.appendChild(newNode);
}
This is what I am trying to achieve:
<parentNode>
<childNode> value1 </childNode>
<childNode> value2 </childNode>
...
<childNode> valueN </childNode>
</parentNode>
The name of child node is not going to change.
Parent node is not a root node.
Can someone please help me figure out what am I missing.
Thanks.
I checked this for you, it looks like it is working as expected to me. What you have perhaps missed is that the changes to your xml are happening in memory? This is what I've done:
input xml file
<rootNode>
<parentNode></parentNode>
</rootNode>
java test class
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
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.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class DocBuilderTest {
private String filePath = "src/test/resource/doc.xml";
#Test
public void builder()
throws ParserConfigurationException, IOException, SAXException, TransformerException {
System.out.println(processFile("parentNode", "value", "childNode"));
}
private String processFile(String parentNode, String value, String childNode)
throws ParserConfigurationException, SAXException, IOException, TransformerException {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filePath);
Node pNode = doc.getElementsByTagName(parentNode).item(0);
for (int i = 0; i < 5; i++) {
String nodeValue = value + i;
Element newNode = doc.createElement(childNode);
newNode.appendChild(doc.createTextNode(nodeValue));
pNode.appendChild(newNode);
}
return toPrettyPrintString(doc);
}
// From https://stackoverflow.com/a/139096/7421645
private String toPrettyPrintString(Document doc) throws TransformerException {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
// initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
return result.getWriter().toString();
}
}
The pretty print reference if the file is already partially indented.
and output to System.out
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<rootNode>
<parentNode>
<childNode>value0</childNode>
<childNode>value1</childNode>
<childNode>value2</childNode>
<childNode>value3</childNode>
<childNode>value4</childNode>
</parentNode>
</rootNode>
NOTE This output is just printed to System.out, I've not overwritten the input file. You'd need to initialise a FileWriter to do that.

Storing sql query in xml file

I want to store sql query in tree format in xml file.I wrote a code which split the code into different tokens and store it in xml file.I am storing keywords like "select",from,where etc as xmlelements and the values of these keywords as textnodes inside corresponding elements.When the query contains single single statement it works as i need.but when nested query occurs i want to store the nested query inside "where" element.In that case the code didn't works properly.I am hereby attaching the code.
Can anyone point out logical mistakes in my code????
Second problem is that when i try to store the xmldata in "CreateFiles.xml" file ,the file is not displaying in the corresponding folder.what is the reason for that?
CreateXml.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Work;
import java.io.File;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
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.Document;
import org.w3c.dom.Element;
/**
*
* #author user
*/
public class Createxmls {
public void CreateXML() throws ParserConfigurationException, TransformerConfigurationException, TransformerException {
DocumentBuilderFactory documentFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentFactory
.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("SQLStatement");
document.appendChild(rootElement);
Element stmt = document.createElement("SQLStatement");
rootElement.appendChild(stmt);
Element Element = document.createElement("null");
String tokens[] = {"select", "max(id)", "from", "facedictionary", "where", "id = (",
"select", "id", "from", "facedetails", "where", "id like 34 group by id)"};
for (int i = 0; i < tokens.length; i++) {
System.out.println("tok:" + tokens[i]);
if (tokens[i].equalsIgnoreCase("select") || tokens[i].equalsIgnoreCase("from") || tokens[i].equalsIgnoreCase("where")) {
Element = document.createElement(tokens[i]);
stmt.appendChild(Element);
} else {
Element.appendChild(document.createTextNode(tokens[i]));
stmt.appendChild(Element);
}
}
String xmlstring = "";
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StreamResult streamResult = new StreamResult(new File(
"createFile.xml"));
StringWriter sw = new StringWriter();
Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.transform(new DOMSource(document), new StreamResult(sw));
xmlstring = sw.toString();
System.out.println(xmlstring);
DOMSource domSource = new DOMSource(stmt);
transformer.transform(domSource, streamResult);
System.out.println("File saved to specified path!");
}
public static void main(String arg[]) {
try {
Createxmls xml = new Createxmls();
xml.CreateXML();
} catch (ParserConfigurationException ex) {
Logger.getLogger(Createxmls.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerConfigurationException ex) {
Logger.getLogger(Createxmls.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerException ex) {
Logger.getLogger(Createxmls.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
When i displayed the contents of xml file for the query:
"select max(id) from facedictionary where id = (select id from facedetails where id like 34 group by id))
The result i got
<?xml version="1.0" encoding="UTF-8"?>
-<SQLStatement>
<select>max(id)</select>
<from>facedictionary</from>
<where>id = (</where>
<select>id</select>
<from>facedetails</from>
<where>id like 34 group by id)</where>
</SQLStatement>
The result i need:
<?xml version="1.0" encoding="UTF-8"?>
-<SQLStatement>
<select>max(id)</select>
<from>facedictionary</from>
<where>id = (
<select>id</select>
<from>facedetails</from>
<where>id like 34 group by id)</where>
</where>
</SQLStatement>

Why my attribute values are not printed?

I am trying to print the attributes values for following xml file:
<data/>
<request/>
<type>City</type>
<query>Jaipur, India</query>
</request>
<current_condition/>
<observation_time>06:37 AM</observation_time>
<temp_C>40</temp_C>
<temp_F>104</temp_F>
<weatherCode>113</weatherCode>
<weatherIconUrl/>
<weatherDesc/>
<windspeedMiles>8</windspeedMiles>
<windspeedKmph>13</windspeedKmph>
<winddirDegree>280</winddirDegree>
<winddir16Point>W</winddir16Point>
<precipMM>0.0</precipMM>
<humidity>34</humidity>
<visibility>4</visibility>
<pressure>997</pressure>
<cloudcover>25</cloudcover>
</current_condition>
<weather/>
<date>2012-07-03</date>
<tempMaxC>46</tempMaxC>
<tempMaxF>115</tempMaxF>
<tempMinC>36</tempMinC>
<tempMinF>97</tempMinF>
<windspeedMiles>6</windspeedMiles>
<windspeedKmph>9</windspeedKmph>
<winddirection>N</winddirection>
<winddir16Point>N</winddir16Point>
<winddirDegree>7</winddirDegree>
<weatherCode>113</weatherCode>
<weatherIconUrl/>
<weatherDesc/>
<precipMM>0.0</precipMM>
</weather>
<weather/>
<date>2012-07-04</date>
<tempMaxC>46</tempMaxC>
<tempMaxF>114</tempMaxF>
<tempMinC>34</tempMinC>
<tempMinF>94</tempMinF>
<windspeedMiles>12</windspeedMiles>
<windspeedKmph>20</windspeedKmph>
<winddirection>NW</winddirection>
<winddir16Point>NW</winddir16Point>
<winddirDegree>319</winddirDegree>
<weatherCode>113</weatherCode>
<weatherIconUrl/>
<weatherDesc/>
<precipMM>0.0</precipMM>
</weather>
</data>
Following is the java code which I am using to print the attribute values:
public class WorldWeatherOnline {
public static void main (String[] args) throws IOException, ParserConfigurationException, SAXException, TransformerException {
URL url = new URL("http://free.worldweatheronline.com/feed/weather.ashx?q=jaipur,india&format=xml&num_of_days=2&key=c5774216f9120304120207");
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
printElementAttributes(doc);
}
static void printElementAttributes(Document doc)
{
NodeList nl = doc.getElementsByTagName("*");
Element e;
Node n;
NamedNodeMap nnm;
String attrname;
String attrval;
int i, len;
len = nl.getLength();
for (int j=0; j < len; j++)
{
e = (Element)nl.item(j);
System.out.println(e.getTagName() + ":");
System.out.println("check-1");
nnm = e.getAttributes();
if (nnm != null)
{
for (i=0; i<nnm.getLength(); i++)
{
System.out.println("check");
n = nnm.item(i);
attrname = n.getNodeName();
attrval = n.getNodeValue();
System.out.print(" " + attrname + " = " + attrval);
}
}
System.out.println();
}
}
Basically my NamedNodeMap nnm is null, so it isn't going inside the loop. I have used these imports:
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.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
Your XML doesn't have any attributes. It just has elements with text contents. An element with an attribute looks like this:
<element attributeName="attribute value" />
If you want to use your current XML, you'll need to get the text values of the elements instead, and presumably store those against the element name.

Categories

Resources