0

I am getting one xml string, that I want to parse and get the data from it. I tried to parse it to json but I get the empty braces as a result.

public class ResultsActivity extends Activity {

    String outputPath;
    TextView tv;
    public static int PRETTY_PRINT_INDENT_FACTOR = 4;
    public static String TEST_XML_STRING;
    DocumentBuilder builder;
    InputStream is;
    Document dom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        tv = new TextView(this);
        setContentView(tv);

        String imageUrl = "unknown";

        Bundle extras = getIntent().getExtras();
        if( extras != null) {
            imageUrl = extras.getString("IMAGE_PATH" );
            outputPath = extras.getString( "RESULT_PATH" );
        }

        // Starting recognition process
        new AsyncProcessTask(this).execute(imageUrl, outputPath);
    }

    public void updateResults(Boolean success) {
        if (!success)
            return;
        try {
            StringBuffer contents = new StringBuffer();

            FileInputStream fis = openFileInput(outputPath);
            try {
                Reader reader = new InputStreamReader(fis, "UTF-8");
                BufferedReader bufReader = new BufferedReader(reader);
                String text = null;
                while ((text = bufReader.readLine()) != null) {
                    contents.append(text).append(System.getProperty("line.separator"));
                }
            } finally {
                fis.close();
            }
        XmlToJson xmlToJson = new XmlToJson.Builder(contents.toString()).build();

// convert to a JSONObject
            JSONObject jsonObject = xmlToJson.toJson();

// OR convert to a Json String
            String jsonString = xmlToJson.toString();

// OR convert to a formatted Json String (with indent & line breaks)
            String formatted = xmlToJson.toFormattedString();
            Log.e("xml",contents.toString());
            Log.e("json",jsonObject.toString());


        } catch (Exception e) {
            displayMessage("Error: " + e.getMessage());
        }
    }


    public void displayMessage( String text )
    {
        tv.post( new MessagePoster( text ) );
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_results, menu);
        return true;
    }

    class MessagePoster implements Runnable {
        public MessagePoster( String message )
        {
            _message = message;
        }

        public void run() {
            tv.append( _message + "\n" );
            setContentView( tv );
        }

        private final String _message;
    }
}

I followed this link : https://github.com/smart-fun/XmlToJson

Can I only parse xml? How can I get the data out of xml string?

Following is the xml string:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://ocrsdk.com/schema/recognizedBusinessCard-1.0.xsd http://ocrsdk.com/schema/recognizedBusinessCard-1.0.xsd" xmlns="http://ocrsdk.com/schema/recognizedBusinessCard-1.0.xsd">
 <businessCard imageRotation="noRotation">
   <field type="Mobile">
     <value>•32147976</value>
   </field>
   <field type="Address">
     <value>Timing: 11:00 a.m. to 5.00 p.m</value>
   </field>
   <field type="Address">
     <value>MULTOWECIALITY HOSPITAL Havnmg Hotel MwyantfwfMf), TOL: 1814 7»7» / 0454 7575 fax: 2514 MSS MtoMte t wvHwJaMtur0Mapttal.com</value>
   </field>
   <field type="Name">
     <value>M. S. (Surgery), Fais, Fics</value>
   </field>
   <field type="Company">
     <value>KASTURI MEDICARE PVT. LTD.</value>
   </field>
   <field type="Job">
     <value>Consulting General Surgeon Special Interest: Medical Administrator: KsturiSecretary: IMA - Mira</value>
   </field>
   <field type="Text">
     <value>Mob.: •32114976
   Dr. Rakhi R
   M. S. (Surgery),  Surgeon
   Special Interest:                               Medical
   President: Bhayander Medical Association
   Scientific Secretary: IMA - Mira Bhayander
   Timing: 11:00 a.m. to 5.00 p.m
   %
   *
   KASTURI MEDICARE PVT. LTD.
   ISO 9001:2008 Certified, ASNH Cliniq 21 Certified,
   MtoMte t wvHwJaMtur0Mapttal.com
   mkhLkasturi0gmoiH.com</value>
   </field>
 </businessCard>

I checked this link to parse the xml: http://androidexample.com/XML_Parsing_-_Android_Example/index.php?view=article_discription&aid=69

But this string dose not have the list, I am not getting how to parse this xml string. Can anyone help please?? Thank you..

3
  • I will give you suggestion that convert it in Json and then parse JsonObject. that will easy than parsing XML. Commented Mar 5, 2017 at 13:20
  • Use XML PullParser to parse XML in android. Commented Mar 5, 2017 at 13:25
  • This is a full example about parsing data with Json , it might help: androidhive.info/2014/07/… Commented Mar 5, 2017 at 13:43

3 Answers 3

1

You can parse Json easily than XML.

So I will suggest you to parse Json,

First Convert XMLto Json then parse the JsonObject.

here is reference you can take to convert XML to JSON Step by Step

https://stackoverflow.com/a/18339178/6676466

Sign up to request clarification or add additional context in comments.

4 Comments

I have tried this, this gives empty braces as a result.
I have tested this code. it works perfect on my side... There will be problem with your xml data.. can you post your xml data...?
got it thank you.. can you help with this question? stackoverflow.com/questions/42612426/…
My pleasure, :) @Sid I have answer your above question. Please check. stackoverflow.com/a/42618406/6676466
1

For Xml parsing you can go for either XML Pull Parser or XML DOM Parser. Both the process are quite lengthy and involves a lot code as it focuses on manual parsing on XML.

Another way is to use This Library in your project and boom most of your job is done. It will parse your XML just like you parse your JSON using GSON. All you need to do is to create a instance of the parser and use it like:

 XmlParserCreator parserCreator = new XmlParserCreator() {
    @Override
    public XmlPullParser createParser() {
      try {
        return XmlPullParserFactory.newInstance().newPullParser();
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  };

  GsonXml gsonXml = new GsonXmlBuilder()
     .setXmlParserCreator(parserCreator)
     .create();

  String xml = "<model><name>my name</name><description>my description</description></model>";
  SimpleModel model = gsonXml.fromXml(xml, SimpleModel.class);

Remember that you need to create a POJO class for your response just like you do for GSON.

Include the library in your gradle using:

compile 'com.stanfy:gson-xml-java:0.1.+'

Please read the github link for library carefully to know the usage and limitations.

Comments

0

from your question I don't get the reason to convert xml to json but just to get a way to fetch some fields out of the xml directly.

If there is no need to process the json data at a later step I recommend you to use XPATH. With Xpath you can get the data of you xml with a simple path query like "/document/businessCard/field[@type='Mobile']/value"

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(URI_TO_YOUR_DOCUMENT);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/document/businessCard/field[@type='Mobile']/value");

1 Comment

and how can I get this in string?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.