[英]How to parse string in which xml. Android
如何从 xml 字符串中获取我需要的数据? 这是我的字符串
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>"
我怎样才能在不同的变量中获得<name>,<balance>,<code>
? 我可以在一个字符串中得到所有答案(String b=" Винт DIN 965 М4*16(2000 шт) Отсутствует 00-00000029 ")
,但我需要得到不同的字符串String one="Винт DIN 965 М4*16(2000 шт)" String two ="Отсутствует", String thr="00-00000029".
对不起我的英语不好)
我试过的这段代码
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
它对我的问题的回答
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.