我是Android的新手,我不知道哪个解析器最好,所以你们可以帮助我解析这个XMl文件
<poem name="P01">
<stanza name="P1S1">
<Line name="P1S1L1">
<word name="P1S1L1W1">Twinkle</word>
<word name="P1S1L1W2">twinkle</word>
<word name="P1S1L1W3">little</word>
<word name="P1S1L1W4">star</word>
</Line>
<Line name="P1S1L2">
<word name="P1S1L2W1">How</word>
<word name="P1S1L2W2">I</word>
<word name="P1S1L2W3">wonder</word>
<word name="P1S1L2W4">what</word>
<word name="P1S1L2W5">you</word>
<word name="P1S1L2W6">are</word>
</Line>
</stanza>
</poem>
我给每个标签提供了Id或Name,我想使用该名称/ ID而不是标签名称来读取标签的文本/值 因为如果我想阅读文本奇迹所以有很多单词标签,那么我怎么能用该名称/ ID读取标签的单个值/文本。 所以请给我这个建议 对不起我的英语不好 Thanx提前
答案 0 :(得分:0)
答案 1 :(得分:0)
使用此代码:
private static void xmlParser() {
try {
String filepath = "yourfile.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
// Get the root element
Node min = doc.getElementsByTagName("poem").item(0);
NamedNodeMap attr = min.getAttributes();
// get the value of the name=
Node nodeAttr = attr.getNamedItem("name");
//if you want to change the value of the name use
nodeAttr.setTextContent("new name value");
//if you want to get the value between >value< use
nodeAttr.getTextContent()
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
只需对上面的其他标签应用以上内容..