I can't fetch text value with Node.getNodeValue(), Node.getFirstChild().getNodeValue() or with Node.getTextContent().
My XML is like
<add job="351">
<tag>foobar</tag>
<tag>foobar2</tag>
</add>
And I'm trying to get tag value (non-text element fetching works fine). My Java code sounds like
Document doc = db.parse(new File(args[0]));
Node n = doc.getFirstChild();
NodeList nl = n.getChildNodes();
Node an,an2;
for (int i=0; i < nl.getLength(); i++) {
an = nl.item(i);
if(an.getNodeType()==Node.ELEMENT_NODE) {
NodeList nl2 = an.getChildNodes();
for(int i2=0; i2<nl2.getLength(); i2++) {
an2 = nl2.item(i2);
// DEBUG PRINTS
System.out.println(an2.getNodeName() + ": type (" + an2.getNodeType() + "):");
if(an2.hasChildNodes())
System.out.println(an2.getFirstChild().getTextContent());
if(an2.hasChildNodes())
System.out.println(an2.getFirstChild().getNodeValue());
System.out.println(an2.getTextContent());
System.out.println(an2.getNodeValue());
}
}
}
It prints out
tag type (1):
tag1
tag1
tag1
null
#text type (3):
_blank line_
_blank line_
...
Thanks for the help.
I'd print out the result of an2.getNodeName() as well for debugging purposes. My guess is that your tree crawling code isn't crawling to the nodes that you think it is. That suspicion is enhanced by the lack of checking for node names in your code.
Other than that, the javadoc for Node defines "getNodeValue()" to return null for Nodes of type Element. Therefore, you really should be using getTextContent(). I'm not sure why that wouldn't give you the text that you want.
Perhaps iterate the children of your tag node and see what types are there?
Tried this code and it works for me:
String xml = "<add job=\"351\">\n" +
" <tag>foobar</tag>\n" +
" <tag>foobar2</tag>\n" +
"</add>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
Document doc = db.parse(bis);
Node n = doc.getFirstChild();
NodeList nl = n.getChildNodes();
Node an,an2;
for (int i=0; i < nl.getLength(); i++) {
an = nl.item(i);
if(an.getNodeType()==Node.ELEMENT_NODE) {
NodeList nl2 = an.getChildNodes();
for(int i2=0; i2<nl2.getLength(); i2++) {
an2 = nl2.item(i2);
// DEBUG PRINTS
System.out.println(an2.getNodeName() + ": type (" + an2.getNodeType() + "):");
if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getTextContent());
if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getNodeValue());
System.out.println(an2.getTextContent());
System.out.println(an2.getNodeValue());
}
}
}
Output was:
#text: type (3): foobar foobar
#text: type (3): foobar2 foobar2
If your XML goes quite deep, you might want to consider using XPath, which comes with your JRE, so you can access the contents far more easily using:
String text = xp.evaluate("//add[#job='351']/tag[position()=1]/text()",
document.getDocumentElement());
Full example:
import static org.junit.Assert.assertEquals;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class XPathTest {
private Document document;
#Before
public void setup() throws Exception {
String xml = "<add job=\"351\"><tag>foobar</tag><tag>foobar2</tag></add>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
document = db.parse(new InputSource(new StringReader(xml)));
}
#Test
public void testXPath() throws Exception {
XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath();
String text = xp.evaluate("//add[#job='351']/tag[position()=1]/text()",
document.getDocumentElement());
assertEquals("foobar", text);
}
}
I use a very old java. Jdk 1.4.08 and I had the same issue. The Node class for me did not had the getTextContent() method. I had to use Node.getFirstChild().getNodeValue() instead of Node.getNodeValue() to get the value of the node. This fixed for me.
If you are open to vtd-xml, which excels at both performance and memory efficiency, below is the code to do what you are looking for...in both XPath and manual navigation... the overall code is much concise and easier to understand ...
import com.ximpleware.*;
public class queryText {
public static void main(String[] s) throws VTDException{
VTDGen vg = new VTDGen();
if (!vg.parseFile("input.xml", true))
return;
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
// first manually navigate
if(vn.toElement(VTDNav.FC,"tag")){
int i= vn.getText();
if (i!=-1){
System.out.println("text ===>"+vn.toString(i));
}
if (vn.toElement(VTDNav.NS,"tag")){
i=vn.getText();
System.out.println("text ===>"+vn.toString(i));
}
}
// second version use XPath
ap.selectXPath("/add/tag/text()");
int i=0;
while((i=ap.evalXPath())!= -1){
System.out.println("text node ====>"+vn.toString(i));
}
}
}
Related
I don't know how to explain my situation, I can provide example below.
I have an XML file to be read in Java, something like this:
<Author AffiliationIDS="Aff1">
<AuthorName DisplayOrder="Western">
<GivenName>Wei</GivenName>
<GivenName>Long</GivenName>
<FamilyName>
<Value>Tan</Value>
</FamilyName>
</AuthorName>
</Author>
As you can see the <FamilyName> tag, inside the <FamilyName> tag is surrounded by a Value tag. This is because in the xsd it stated the element as maxOccurs="unbounded" which mean more than one value can be in that element tag. How should I modify the code so that it can read in the <FamilyName> tag and get Value tag element no matter how many occurrence of the Value exist?
Example:
<FamilyName>
<Value>Sarah</Value>
<Value>Johnson</Value>
</FamilyName>
The code look like this.
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("/fileaddress/test-1.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("AuthorName");
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("Given Name : " + eElement.getElementsByTagName("GivenName").item(0).getTextContent());
System.out.println("Family Name : " + eElement.getElementsByTagName("FamilyName").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Get the FamilyName node by getElementsByTagName("FamilyName").item(0) and loop over its child nodes (.getChildNodes()) and get the value of the textNode
Or,
You can even getElementsByTagName("Value") if you are sure that value tag does not occur anywhere else other than inside FamilyName
Here is a code Sample
NodeList children = doc.getElementsByTagName("FamilyName").item(0).getChildNodes();
for(int i=0;i<children.getLength();i++) {
if(children.item(i).getNodeType()== Node.ELEMENT_NODE) {
Element child = (Element)children.item(i);
System.out.println(child.getTextContent());
}
}
I know there was a lot of answers about this question but all didn't work in my case. I would read data from European Central Bank from this link ECB. For example, how to read "rate" of USD where time="2015-02-27" and how to read "rate" of USD from all 90 days ?
One of the simplest ways to do it is to use a DOM (Document Object Model) parser. It will load your xml document in memory and turns it into a tree made of Nodes so that you can travers it being able to get the information of any node at any position. It is memory consumming and is generally less prefered than a SAX parser.
Here is an example:
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 DomParsing {
public static final String ECB_DATAS ="C:\\xml\\eurofxref-hist-90d.xml";
public static void main(String argv[]) {
try {
File fXmlFile = new File(ECB_DATAS);
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("Cube");
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("currency : " + eElement.getAttribute("currency") + " and rate is " + eElement.getAttribute("rate"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Applied to your file produces the following result:
currency : BGN and rate is 1.9558
Current Element :Cube
currency : CZK and rate is 27.797
Current Element :Cube
currency : DKK and rate is 7.444
I have the below plist.
<?xml version="1.5" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//PSect//ACD PLIST 1.5//" "http://pset.com/ACD/plist.dtd">
<plist version="1.5">
<dict>
<key>City</key>
<string>Melbourne</string>
<key>DetailedInfo</key>
<dict>
<key>Name</key>
<real>Sam</real>
<key>Income</key>
<real>4000</real>
</dict>
<key>Status</key>
<string>Single</string>
<key>PIN</key>
<string>123456789</string>
</dict>
I have the code to parse this plist into an xml file. What I need help with is to find the key City in the plist. I have looked at some posts to search for a string in an xml file, but haven't had much luck. Basically what I want to do is,
1. Check if my xml file has Key City
2. If it does, assign its value (Melbourne) to another String.
Is there anyway I can achieve this? Please suggest.
i am not sure of the doctype you have in your plist but try this
try this
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class Demo {
public static void main(String[] args) throws Exception {
String keyVal = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File("input.xml"));
NodeList keyList = document.getElementsByTagName("key");
if(keyList !=null && keyList.getLength() > 0) {
for(int i =0; i< keyList.getLength(); i++) {
keyVal = keyList.item(i).getTextContent();
if ("City".equals(keyVal)) {
NodeList stringList = document.getElementsByTagName("string");
if(stringList !=null && stringList.getLength() > 0) {
System.out.println(stringList.item(i).getTextContent());
}
}
}
}
}
}
XPath path = XPathFactory.newInstance().newXPath();
NodeList nl = (NodeList) path.evaluate("//dict[key/text()='City']", doc, XPathConstants.NODESET);
if (nl.getLength() == 1) {
Element dictElement = (Element) nl.item(0);
NodeList stringNodeList = dictElement.getElementsByTagName("string");
for (int i = 0; i < stringNodeList.getLength(); i++) {
// replace string here
System.out.println("Replace: " + stringNodeList.item(i));
}
}
why don't you use object-xml binding framework like jaxb or xtream to do this. Those frameworks would create an object out of your xml and it will be very easy to navigate this xml then. for example you could do if("City".equals(getDict().getKey()) { then do this}
my question is "DOM parser, why do I get just one child of an element?"
I looked into this and this one, but I do not get the point.
What I'm trying to do is the following:
I have an XML file (see the extract below) :
<POITEM>
<item>
<PO_ITEM>00010</PO_ITEM>
<SHORT_TEXT>ITEM_A</SHORT_TEXT>
<MATL_GROUP>20010102</MATL_GROUP>
<AGREEMENT>4600010076</AGREEMENT>
<AGMT_ITEM>00010</AGMT_ITEM>
<HL_ITEM>00000</HL_ITEM>
<NET_PRICE>1.000000000</NET_PRICE>
<QUANTITY>1.000</QUANTITY>
<PO_UNIT>EA</PO_UNIT>
</item>
<item>
<PO_ITEM>00020</PO_ITEM>
<SHORT_TEXT>ITEM_B</SHORT_TEXT>
<MATL_GROUP>20010102</MATL_GROUP>
<AGREEMENT>4600010080</AGREEMENT>
<AGMT_ITEM>00020</AGMT_ITEM>
<HL_ITEM>00000</HL_ITEM
<NET_PRICE>5.000000000</NET_PRICE>
<QUANTITY>5.000</QUANTITY>
<PO_UNIT>EA</PO_UNIT>
</item>
</POITEM>
I only want to extract <PO_ITEM>, <SHORT_TEXT>, <MATL_GROUP>, <NET_PRICE>, <QUANTITY> and <PO_UNIT> and write it into another, smaller XML file.
So this is my code:
nodes = dcmt.getElementsByTagName("POITEM");
Element rootElement2 = doc1.createElement("PO_POSITIONS");
rootElement1.appendChild(rootElement2);
Element details2 = doc1.createElement("PO_DETAILS");
rootElement2.appendChild(details2);
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
Element position = doc1.createElement("position");
details2.appendChild(position);
Element poItm = doc1.createElement("PO_ITEM");
poItm.appendChild(doc1.createTextNode(getValue("PO_ITEM", element)));
position.appendChild(poItm);
Element matlGrp = doc1.createElement("MATL_GROUP");
matlGrp.appendChild(doc1.createTextNode(getValue("MATL_GROUP",element)));
position.appendChild(matlGrp);
Element poUnit = doc1.createElement("PO_UNIT");
poUnit.appendChild(doc1.createTextNode(getValue("PO_UNIT",element)));
position.appendChild(poUnit);
Element netPrice = doc1.createElement("NET_PRICE");
netPrice.appendChild(doc1.createTextNode(getValue("NET_PRICE",element)));
position.appendChild(netPrice);
Element shortTxt = doc1.createElement("SHORT_TEXT");
shortTxt.appendChild(doc1.createTextNode(getValue("SHORT_TEXT",element)));
position.appendChild(shortTxt);
//Element matl = doc2.createElement("MATERIAL");
//matl.appendChild(doc2.createTextNode(getValue("MATERIAL",element)));
//details2.appendChild(matl);
Element qnty = doc1.createElement("QUANTITY");
qnty.appendChild(doc1.createTextNode(getValue("QUANTITY",element)));
position.appendChild(qnty);
/*Element preqNr = doc1.createElement("PREQ_NO");
preqNr.appendChild(doc1.createTextNode(getValue("PREQ_NO",element)));
details2.appendChild(preqNr); */
}
}
So far so good, I'm getting a new XML File, but it only holds the first entry, so as i understand it, by the nodes = dcmt.getElementsByTagName("POITEM"); gets into the first <item> until the first </item> and then gets out of the loop. So how do I manage step into the next item? Do I need to create some kind of loop, to access the next <item> ?
By the way, changing the structure of the XML file is no option, since I get the file from an interface.
Or do I make a mistake while writing the new XML file?
The output looks like this:
<PO_POSITIONS>
<PO_DETAILS>
<position>
<PO_ITEM>00010</PO_ITEM>
<MATL_GROUP>20010102</MATL_GROUP>
<PO_UNIT>EA</PO_UNIT>
<NET_PRICE>1.00000000</NET_PRICE>
<SHORT_TEXT>ITEM_A</SHORT_TEXT>
<QUANTITY>1.000</QUANTITY>
</position>
</PO_DETAILS>
</PO_POSITIONS>
You could parse it yourself, it's kind of a pain. When I did xml way back when, we used to use stylesheets to do these kinds of transformations. Something like this post: How to transform XML with XSL using Java
If that's not an option, then to do it by hand (I omitted the new document construction, but you can see where it goes):
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLTest {
#Test
public void testXmlParsing() throws Exception {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new File("/Users/aakture/Documents/workspace-sts-2.9.1.RELEASE/smartfox/branches/trunk/java/gelato/src/test/resources/sample.xml").getAbsolutePath());
Node poItem = doc.getElementsByTagName("POITEM").item(0);
NodeList poItemChildren = poItem.getChildNodes();
for (int i = 0; i < poItemChildren.getLength(); i++) {
Node item = poItemChildren.item(i);
NodeList itemChildren = item.getChildNodes();
for (int j = 0; j < itemChildren.getLength(); j++) {
Node itemChild = itemChildren.item(j);
if("PO_ITEM".equals(itemChild.getNodeName())) {
System.out.println("found PO_ITEM: " + itemChild.getTextContent());
}
if("MATL_GROUP".equals(itemChild.getNodeName())) {
System.out.println("found MATL_GROUP: " + itemChild.getTextContent());
}
}
}
}
}
I've got an app that consumes a .NET web service which returns an XML string of data. I'm trying to read this XML and insert it into the local SQLite DB but I'm having some trouble. Here's a sample of the xml:
<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="RemoteWebService"><OpenIssues> <Table> <IssueID>15351</IssueID> <IssueSummary>Computer keeps crashing. This continues to be a problem</IssueSummary> <LocationName>West Side</LocationName> <Status>WIP</Status> <CustomerID>89755</CustomerID> <CustomerName>West Side Computers</CustomerName> <CustomerShortName>WSC</CustomerShortName> <Notes /> <STATUS1>Work In Progress</STATUS1> <SubmittedBy>WSC - Tom Johns</SubmittedBy> <EQ_Replaced>true</EQ_Replaced></Table> </OpenIssues></string>
Using DOM, I'm trying to parse the results like so:
private void GetLatestData(String response) throws ParserConfigurationException, SAXException, IOException{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(response)));
//Normalize the document.
doc.getDocumentElement().normalize();
//Get Root Node.
NodeList nodeList = doc.getElementsByTagName("Table");
Node node = nodeList.item(0);
//Get Child Nodes.
for(int i = 0; i < node.getChildNodes().getLength(); i++){
IssueInfo issue = new IssueInfo();
Node tempNode = node.getChildNodes().item(i);
if(tempNode.getNodeName().equalsIgnoreCase("IssueID")){
issue.setIssueNumber(Long.parseLong(tempNode.getTextContent()));
}
if(tempNode.getNodeName().equalsIgnoreCase("IssueSummary")){
issue.setIssueNumber(Long.parseLong(tempNode.getTextContent()));
}
if(issue.getIssueNumber() > 0 && issue.getIssueSummary() != null){
creator = new IssueInfoCreator(this, DBVersion);
creator.open();
creator.InsertIssue(issue.getIssueNumber(), DateFormat.getDateInstance().format(new Date()), issue.getIssueSummary());
creator.close();
}
}
}
When I run it through the debugger, it gets "IssueID" just fine but how can I get it to pickup the next node "IssueSummary" right after that so I can insert the data at once? It seems like I need another loop somewhere, just not too sure where though.
If I understand your question correctly, this is what you may need to do.
Node node = nodeList.item(0);
Returns
<Table>
<IssueID>15351</IssueID>
<IssueSummary>Computer keeps crashing. This continues to be a problem</IssueSummary>
<Notes />
</Table>
node.getChildNodes().getLength();
Returns 3.
IssueInfo issue = new IssueInfo();
// Go through each child and find out node name and populate it.
for(int i = 0; i < node.getChildNodes().getLength(); i++){
Node tempNode = node.getChildNodes().item(i);
if(tempNode.getNodeName().equalsIgnoreCase("IssueID")){
issue.setIssueNumber(Long.parseLong(tempNode.getTextContent()));
}
if(tempNode.getNodeName().equalsIgnoreCase("IssueSummary")){
issue.setIssueNumber(Long.parseLong(tempNode.getTextContent()));
}
}
Move if logic out of the loop.
if(issue.getIssueNumber() > 0 && issue.getIssueSummary() != null){
creator = new IssueInfoCreator(this, DBVersion);
creator.open();
creator.InsertIssue(issue.getIssueNumber(), DateFormat.getDateInstance().format(new Date()), issue.getIssueSummary());
creator.close();
}
Seems like a simple DOM traversing issue.
If you can guarantee the next node is the summary, you could try using the getNextSibling() method for nodes
I modified your code so I could call it without using your classes. This is the code I used:
private static void GetLatestData(String response) {
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
/* the following 2 lines help you eliminate whitespace
from your xml DOM tree */
dbf.setValidating(true);
dbf.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = dbf.newDocumentBuilder();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(response)));
//Normalize the document.
doc.getDocumentElement().normalize();
//Get Root Node.
NodeList nodeList = doc.getElementsByTagName("Table");
Node node = nodeList.item(0);
long issueNumber;
String summary;
//Get Child Nodes.
for(int i = 0; i < node.getChildNodes().getLength(); i++){
Node tempNode = node.getChildNodes().item(i);
if(tempNode.getNodeName().equalsIgnoreCase("IssueID")){
issueNumber = (Long.parseLong(tempNode.getTextContent()));
Node summaryNode = tempNode.getNextSibling();
summary = summaryNode.getTextContent();
System.out.println(String.format("Issue # %d, Summary: %s" , issueNumber,summary));
}
}
}catch(Exception exception){
exception.printStackTrace();
}
}
and I call it like this:
GetLatestData("<OpenIssues> " +
"<Table> " +
"<IssueID>15351</IssueID>" +
"<IssueSummary>Computer keeps crashing. This continues to be a problem</IssueSummary> " +
"<Notes />" +
"</Table></OpenIssues> ");
from a simple Java class. It's working all right for me, at least. It prints out:
Issue # 15351, Summary: Computer keeps crashing. This continues to be a problem
*smacks forehead*
issue will never have more than one value set, as it's created anew for each child node.
Just swap the two lines to create issue only once:
IssueInfo issue = new IssueInfo();
for(int i = 0; i < node.getChildNodes().getLength(); i++){
...
You should probably move the final if outside the for too, so it's not executed more than once.
AND you'll need to actually set the summary in the second if not. You're setting the 'issue number' twice.
Finally found the resolution to this with the help of my coworker and some digging around. It should be noted that we changed the WebService that returned a string from DataSet.GetXml() to an XmlDocument.InnerXml. This removed the spaces in between the nodes and then we were able to move forward from there. Here's the final code we used:
public void GetLatestData(SoapPrimitive xml)throws ParserConfigurationException, SAXException, IOException{
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc;
//parse using builder to get DOM representation of the XML file
InputSource is = new InputSource(new StringReader(xml.toString()));
doc = db.parse(is);
//Clear out Issues table first.
creator = new IssueInfoCreator(this, DBVersion);
creator.open();
creator.ClearIssueTable();
creator.close();
NodeList nodes = doc.getElementsByTagName("Table");
for(int i = 0; i < nodes.getLength(); i++) {
IssueInfo issue = new IssueInfo();
Element e = (Element)nodes.item(i);
issue.setIssueNumber(Long.parseLong(XMLfunctions.getValue(e, "IssueID")));
issue.setIssueSummary(XMLfunctions.getValue(e, "IssueSummary"));
issue.setDateReceived(DateFormat.format("MM/dd/yyyy hh:mm:ss", System.currentTimeMillis()).toString());
if(issue.getIssueNumber() > 0 && issue.getIssueSummary() != null){
creator = new IssueInfoCreator(this, DBVersion);
creator.open();
creator.InsertIssue(issue.getIssueNumber(), issue.getDateReceived(), issue.getIssueSummary());
creator.close();
}
}
}
And here is the getValue method of the XMLfuntions class:
public static String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return XMLfunctions.getElementValue(n.item(0));
}
public final static String getElementValue( Node elem ) {
Node kid;
if( elem != null){
if (elem.hasChildNodes()){
for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
if( kid.getNodeType() == Node.TEXT_NODE ){
return kid.getNodeValue();
}
}
}
}
return "";
}
Definately not taking credit for this, I found it here:
Programmer XR and modified it to my needs.
Hopefully this will help other people out!