0

我是 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 或名称,并且我想使用该名称/ID 而不是标签名称来读取标签的文本/值,因为如果我想阅读文本奇迹,那么有很多单词标签,那么我该如何阅读使用该名称/ID 的标签的单个值/文本。所以请提前给我关于这个对不起我的英语谢谢的建议

4

2 回答 2

0

这很容易。您应该使用 DOM 解析器。

这是一个链接

您也可以进行 SAX 解析,但这相当复杂。

于 2013-05-30T06:34:48.607 回答
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();
        }
}

只需将上述内容应用于其余标签..

于 2013-05-30T06:38:48.193 回答