-3

I have a String variable in java with xml tags as its value:

eg: String xml="<root><name>abcd</name><age>22</age><gender>male</gender></root>";

Now I need to get the value within the name tag i.e "abcd" from this variable and store the value in another string variable. How to go about this using java. Can anyone please help me out with this?

codecrazy46
  • 275
  • 1
  • 5
  • 14

1 Answers1

1

It is not quite clear what you want, but I think what you will need is something to read an XML document (as a file or directly as a string), an XML parser.

There is a whole list (and many more) of different XML parsers you can use for this:

I would recommend dom4j for its easy usage. Here is an example for a dom4j implemenation:

String xmlPath = "myXmlDocument.xml";

SAXReader reader = new SAXReader();
Document document = reader.read(xmlPath);
Element rootElement = document.getRootElement();
System.out.println("Root Element: "+rootElement.getName());

You can directly feed in a String to be parsed to an XML document too:

String xmlString = "<name>Hello</name>";

SAXReader reader = new SAXReader();
Document document = DocumentHelper.parseText(xmlString);
Element rootElement = document.getRootElement();
System.out.println("Root Element: "+rootElement.getName());

References

Community
  • 1
  • 1
flotothemoon
  • 1,882
  • 2
  • 20
  • 37
  • Thanks for the info but I need to find the value based on tag names. eg: 22 for age tag. How do I achieve this. Please help me out with this. – codecrazy46 Aug 02 '14 at 03:37