2 replies Latest Post - ‏2011-05-04T15:16:40Z by bweekender
2 Posts

Pinned topic how to get tag id value

‏2011-05-04T01:16:24Z |
Java/XML newb:

I have a small xml database, that looks like this snippet:

<?xml version="1.0" encoding="ISO-8859-1"?>
<tag_database xmlns="http://a.b.c/simple" last_changed_date="blah">
<tag id="0">

My code (snippet) looks like this:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
NodeList nodeLst = doc.getElementsByTagName("tag");
int numNodes = nodeLst.getLength();

for (ints = 0; s< numNodes; s++)
Node curNode = nodeLst.item(s);
if (curNode.getNodeType() == Node.ELEMENT_NODE)
Element fstElmnt = (Element) curNode;
NodeList tagElmntLst = fstElmnt.getElementsByTagName("tag");
Element tagElmnt = (Element) tagElmntLst.item(0);
//System.out.println("TagName : " + tagElmnt.getAttribute("tag")); ERRORS!!!

I am just trying to get the value associated with "tag id" (ie: "0").
Any help is truly appreciated.
Updated on 2011-05-04T15:16:40Z at 2011-05-04T15:16:40Z by bweekender
  • SystemAdmin
    1830 Posts

    Re: how to get tag id value

    ‏2011-05-04T10:37:13Z  in response to bweekender
    You've applied getElementsByTagName("tag") twice: that certain is not the intention. And then to get to attribute "id", you applied getAttribute("tag"), surely wrong. And then getElementsByTagName() gets nodes of Element type, hence testing their node type seems pointless. And then, the whole block is based on the factory's turning a blind eye on namespace (dbf's setNamespaceAware(false) by default)---if you don't understand what this means, you've to do more homework. Although it can make work, but your unawareness of that fundamental fact seems worrying.
    for (
    int s = 0; s< numNodes; s++) 
    { Element tagElmnt = (Element) nodeLst.item(s); System.out.println(
    "Attribute id : " + tagElmnt.getAttribute(
    • bweekender
      2 Posts

      Re: how to get tag id value

      ‏2011-05-04T15:16:40Z  in response to SystemAdmin
      Thank you kindly for your response. I am a new-b to both Java and XML, being an avid C/C++ programmer for too long ;-), and have been tasked with writing a "fast test case" in Java.

      I hope to get the time to learn more about the Java/XML, but meanwhile, your answer was just what I was looking for.