0

我的 XML 如下所示

<?xml version="1.0" encoding="UTF-8"?>
<Students>
<![CDATA[<?xml version="1.0" encoding="UTF-8"?> <Student><rno>1</rno><name>xyz</name>     </student>]]>
</Students>

在 XSL 的帮助下,我想检索 cdata 部分中存在的 rno 的值。我如何读取这个值

4

1 回答 1

0

首先,在您的 xml 中,您应该替换</student></Student>. 因为这里的 XML 标签是区分大小写的引用

自己做到这一点的诀窍如下:

public static String getRNO(){

    String valueRetrieved = null;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = null;
    Document doc = null;

    try {
        db = dbf.newDocumentBuilder();
        doc = db.parse(new File("D:\\Loic_Workspace\\Test2\\res\\test.xml"));
        NodeList ndList = doc.getElementsByTagName("Students");
        String xmlRetrieved = ndList.item(0).getTextContent();

        if(xmlRetrieved != null) {
            //CALL OF STRING REPLACE METHOD TO PREVENT FROM
            //at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
            //at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source
            xmlRetrieved = xmlRetrieved.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");

            doc = db.parse(new InputSource(new StringReader(xmlRetrieved)));
            valueRetrieved = doc.getElementsByTagName("rno").item(0).getTextContent();
        }


    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    return valueRetrieved;

}

希望能帮助到你 ;-)

于 2013-02-03T20:41:46.283 回答