1

I came across phase in my code that I need to convert an Element object into int when I know that the Element object holds an int. But I can't seem to find a way to convert that into an int. Here is the code:

       // extract data from XML file 
       NodeList roundNumber = element.getElementsByTagName("roundNumber");
       Element line = (Element) roundNumber.item(0);

       // now convert "line" into an int 

How can I convert the line Element into an int ?

Rob Hruska
  • 115,151
  • 29
  • 164
  • 188
JAN
  • 20,056
  • 54
  • 170
  • 290
  • 4
    Do you mean the `roundNumber` element contains text that represents an integer? If so, try calling `line.getTextContent()` and passing that to, say, `Integer.parseInt()`. – Rob I May 09 '12 at 19:40
  • 1
    I don't do a lot with DOM `Element`s in Java, but perhaps you could use a combination of [this](http://docs.oracle.com/javase/6/docs/api/org/w3c/dom/Node.html#getTextContent()) and [this](http://stackoverflow.com/questions/5585779). – Rob Hruska May 09 '12 at 19:41
  • @RobI That your comment should be an answer. – Jim Garrison May 09 '12 at 19:45
  • @Jim - I hesitate to make it an answer since it's essentially just a link to another SO question. The API link isn't, but I also don't have enough experience using `Element` to speak authoritatively on it. There may be a better API method or something. – Rob Hruska May 09 '12 at 19:46

2 Answers2

5
int number = Integer.parseInt(line.getTextContent());

Be sure that line.getTextContext() always returns an integer, or a NumberFormatException will be thrown.

elias
  • 14,050
  • 4
  • 37
  • 63
  • 2
    Just a comment, wrap this sentence in a try-catch block catching NumberFormatException just as a defensive programming tactic. – Fritz May 09 '12 at 19:55
  • But the best practice is to validate the XML using a XSD before do something like that, or `line.getTextContent().matches("\\d+")` taking care with the size of number. – elias May 10 '12 at 20:22
1

if you know the name of the attribute you can do the following :

Integer.valueOf(line.getAttribute("<attribute name>"));
Sanjeev
  • 1,327
  • 15
  • 28