如何从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();
}