0

My XML will look like:

< Header>
    < Feature web="true" mob="false" app="true">some data< /feature>
< /Header>

I want java file with the data of web, mob, app in boolean and the somedata as string in java. How to extract data from xml? Please help

PDJ
  • 69
  • 8
  • I would use XPath: http://stackoverflow.com/questions/340787/parsing-xml-with-xpath-in-java – Thilo Dec 05 '14 at 05:58

1 Answers1

0

You can use XML transformation provided by java. This will return you something called dom objects which you can use for retrieving whatever data you have in the xml. In you case some attributes of feature tag and others.

Following this tutorial https://docs.oracle.com/javase/tutorial/jaxp/dom/readingXML.html

Sample code to quickly try it ;-)

public class TransformXml {

    public static void main(String[] args) {
        String xmlStr = "<Header><feature web=\"true\" mob=\"false\" app=\"true\">some data</feature></Header>";

        Document doc = convertStringToDocument(xmlStr);

        String str = convertDocumentToString(doc);
        System.out.println(str);
    }

    private static String convertDocumentToString(Document doc) {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;
        try {
            transformer = tf.newTransformer();
            // below code to remove XML declaration
            // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
            // "yes");
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(doc), new StreamResult(writer));
            String output = writer.getBuffer().toString();
            return output;
        } catch (TransformerException e) {
            e.printStackTrace();
        }

        return null;
    }

    private static Document convertStringToDocument(String xmlStr) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        try {
            builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(xmlStr)));
            return doc;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
atish shimpi
  • 4,873
  • 2
  • 32
  • 50
Chetan Naik
  • 53
  • 1
  • 5