0

I have a JAVA string that is holding an XML document. What is the easiest way to parse the string and extract the value, in this case "abc" from the following:

<...>
    <book>abc</book>
</...>

Thanks

Alex
  • 33
  • 1
  • 7
  • In my personal opinion, XPath is powerful tools to extract information from XML : http://stackoverflow.com/questions/2811001/how-to-read-xml-using-xpath-in-java , for this particular XML the XPath expression would be as simple as : `//book` – har07 Dec 06 '15 at 06:23

1 Answers1

1

Try code of these links :

How to parse a String containing XML in Java and retrieve the value of the root node?

http://www.java2s.com/Code/Java/XML/ParseanXMLstringUsingDOMandaStringReader.htm

Community
  • 1
  • 1
bob
  • 4,595
  • 2
  • 25
  • 35
  • String xml = "HELLO!"; org.jdom.input.SAXBuilder saxBuilder = new SAXBuilder(); try { org.jdom.Document doc = saxBuilder.build(new StringReader(xml)); String message = doc.getRootElement().getText(); System.out.println(message); } catch (JDOMException e) { // handle JDOMException } catch (IOException e) { // handle IOException } If I use this code, I get an error saying pacakage org.jdom.input does not exist. Where can I get it from? I'm new to java. – Alex Dec 06 '15 at 04:44
  • @Alex You need to add the JDOM2 dependency to your project. To find out how to do that, just google ` add library` and use the JDOM2 jar you get from [here](http://www.jdom.org/downloads/index.html) (click "JDOM 2.0.6") – randers Dec 06 '15 at 09:52
  • Thank you for your help. How can I get value of a child element using JDOM? – Alex Dec 09 '15 at 03:04