XML和DOM获取#text输出

时间:2010-11-26 18:21:37

标签: java xml dom

我正在尝试通过遍历子节点列表来读取Collada XML文件,并且每个其他输出都读取#text。这是关于什么的?我的代码:

public void runTest() {
    File file = new File( "test.dae" );
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    try {
        builder = factory.newDocumentBuilder();
    }
    catch( ParserConfigurationException error ) {
        System.out.println( "--ParserConfigurationException: " + error.getMessage() ); return;
    }
    Document document = null;
    try {
        document = builder.parse( file );
    }
    catch( IOException error ) {
        System.out.println( "--IOException: " + error.getMessage() ); return;
    }
    catch( SAXException error ) {
        System.out.println( "--SAXException: " + error.getMessage() ); return;
    }
    Node node = document.getDocumentElement();
    String node_name = node.getNodeName();
    System.out.println( node_name );
    NodeList node_list = node.getChildNodes();
    for( int iterator = 0; iterator < node_list.getLength(); iterator++ ) {
        Node child_node = node_list.item( iterator );
        String child_node_name = child_node.getNodeName();
    System.out.println( "-- " + child_node_name );
    }
}

1 个答案:

答案 0 :(得分:4)

“#text”只是在Text节点上调用getNodeName()方法的结果。 (正如您将看到org.w3c.dom.Node的API文档一样。)如果您想要节点的实际文本内容,可以使用getNodeValue()方法。

如果您不希望有任何Text节点,请不要忘记即使是一些空白字符,如新行字符,也会被视为文本。