我有一个名为XmlResourceParser
的{{1}}个实例。当我尝试在节点上调用xml
时,如我的代码所示,它返回null。这很奇怪,因为我可以在同一节点上调用getText()
它返回正确的值,因此实例设置正确。这是我的代码:
getName()
这是我的XML,即使它没有任何问题:
XmlResourceParser xml = context.getResources().getXml(R.xml.thesaurus);
try {
//if (xml.getName().equals("word")) {
xml.next(); //to the first node within <word></word>
boolean notFound = true;
while (notFound) {
xml.next();
if (xml.getName() != null && xml.getName().equalsIgnoreCase("synonyms")) {
String synonym = xml.getText();
Log.v(TAG, String.valueOf(synonym));
notFound = false; //found
}
}
}
} catch (XmlPullParserException xppe) {
xppe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
任何帮助将不胜感激!谢谢!
答案 0 :(得分:2)
我找到了自己的答案here.我使用了@Libin在这个答案中发布的代码。
int eventType = xmlResourceParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if (eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag " + xmlResourceParser.getName());
} else if (eventType == XmlPullParser.END_TAG) {
System.out.println("End tag " + xmlResourceParser.getName());
} else if (eventType == XmlPullParser.TEXT) {
System.out.println("Text " + xmlResourceParser.getText());
}
eventType = xmlResourceParser.next();
}
感谢大家的帮助
答案 1 :(得分:0)
当您调用xml.getText()时,xml解析器当前指向START_TAG,而不是内容。调用xml.next()让getText()返回内容:
if (xml.getName() != null && xml.getName().equalsIgnoreCase("synonyms")) {
xml.next();
String synonym = xml.getText();
Log.v(TAG, String.valueOf(synonym));
notFound = false; //found
}
您可以使用以下命令验证迭代器位置:
if (xml.getEventType() == XmlPullParser.TEXT) {
// iterator is at content
}
答案 2 :(得分:-1)
试试这个
final String xml ="<?xml version=\"1.0\"?><thesaurus><word name=\"let\"><synonyms>allow</synonyms></word></thesaurus>";
final DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = builderFactory.newDocumentBuilder();
final Document xmlDocument = builder.parse(new ByteArrayInputStream(xml.getBytes()));
final XPath xPath = XPathFactory.newInstance().newXPath();
final Object result = xPath.compile("/thesaurus/word/synonyms").evaluate(xmlDocument, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int h = 0; h < nodes.getLength(); h++) {
final Node node = nodes.item(h);
final NodeList venueChildNodes = node.getChildNodes();
System.out.println(node.getChildNodes().item(0).getTextContent());
}
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
}