简体   繁体   English

如何解析 xml 中的字符串。 Android

[英]How to parse string in which xml. Android

How can I get the data that I need from an xml string?如何从 xml 字符串中获取我需要的数据? This is my string这是我的字符串

String a="<?xml version=\"1.0\"?>\n" +
            "<answer>\n" +
            "\t<name>Винт DIN 965 М4*16(2000 шт)</name>\n" +
            "\t<balance>Отсутствует</balance>\n" +
            "\t<code>00-00000029</code>\n" +
            "</answer>"

How i can get <name>,<balance>,<code> in different variables?我怎样才能在不同的变量中获得<name>,<balance>,<code> I can get all answer in one string (String b=" Винт DIN 965 М4*16(2000 шт) Отсутствует 00-00000029 ") , but i need get in differentr string String one="Винт DIN 965 М4*16(2000 шт)" String two ="Отсутствует", String thr="00-00000029".我可以在一个字符串中得到所有答案(String b=" Винт DIN 965 М4*16(2000 шт) Отсутствует 00-00000029 ") ,但我需要得到不同的字符串String one="Винт DIN 965 М4*16(2000 шт)" String two ="Отсутствует", String thr="00-00000029". Sorry for my English)对不起我的英语不好)

This code i tried我试过的这段代码

DocumentBuilder newDocumentBuilder = null;
                try {
                    newDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                } catch (ParserConfigurationException e) {
                    e.printStackTrace();
                }
                Document parse = null;
                try {
                    parse = newDocumentBuilder.parse(new InputSource(new StringReader(answer)));
                } catch (SAXException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }Винт DIN 965 М4*16(2000 шт)
    Отсутствует
    00-00000029`enter code here`
System.out.print(parse.getFirstChild().getTextContent();)  // Винт DIN 965 М4*16(2000 шт) Отсутствует 00-00000029

Its answer for my question它对我的问题的回答



                                        XPathFactory xpathFactory = XPathFactory.newInstance();
                                        XPath xpath = xpathFactory.newXPath();
                                        InputSource source = new InputSource(new StringReader(ss));

                                        Document doc = (Document) xpath.evaluate("/", source, XPathConstants.NODE);
                                        postName = xpath.evaluate("/answer/name", doc);
                                        postBalance = xpath.evaluate("/answer/balance", doc);
                                        String bal = xpath.evaluate("/answer/code", doc);
                                        tvPost.setText(postName);
                                        tvPostBalance.setText(postBalance);

                                    } catch (XPathExpressionException e) {
                                        e.printStackTrace();
                                    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM