如何解析xml并从xml字符串中获取数据?

时间:2017-03-05 13:17:10

标签: java android json xml parsing

我正在获取一个xml字符串,我想解析并从中获取数据。我试图将它解析为json但是我得到了空括号。

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;
    }
}

我点了这个链接:https://github.com/smart-fun/XmlToJson

我可以只解析xml吗?如何从xml字符串中获取数据?

以下是xml字符串:

<?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>

我检查了此链接以解析xml:http://androidexample.com/XML_Parsing_-_Android_Example/index.php?view=article_discription&aid=69

但是这个字符串没有列表,我没有得到如何解析这个xml字符串。有人可以帮忙吗?谢谢..

3 个答案:

答案 0 :(得分:1)

您可以轻松解析Json,而不是XML

所以我建议你解析Json,

首先将XML转换为Jso n,然后解析JsonObject

这里是您可以参考将XML转换为JSON的步骤

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

答案 1 :(得分:0)

对于Xml解析,您可以选择XML Pull ParserXML DOM Parser。 这个过程都非常冗长,涉及很多代码,因为它侧重于对XML进行手动解析。

另一种方法是在项目中使用This Library,并且大部分工作都已完成。它将解析您的XML,就像您使用GSON解析JSON一样。 您需要做的就是创建解析器的实例并使用它:

 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);

请记住,您需要为响应创建一个POJO类,就像您为GSON一样。

使用以下方法将库包含在您的gradle中:

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

请仔细阅读图书馆的github链接,了解其用途和限制。

答案 2 :(得分:0)

从您的问题

我没有理由将xml转换为json,只是为了找到一种方法直接从xml中获取一些字段。

如果以后不需要处理json数据,我建议您使用XPATH。使用Xpath,您可以通过简单的路径查询获取xml的数据,例如“/ 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");