有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么Element::GetElementsByTagnames失败?

给定XML实例文档:

<foo:A xmlns:foo="http://foo" >
    <foo:ListRecords>
        <foo:record>
        </foo:record>
    </foo:ListRecords>
</foo:A>

以下代码:

import java.io.File;

import javax.xml.parsers.*;
import org.w3c.dom.*;


public class FooMain {

    public static void main(String args[]) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new File("record.xml"));
        Element rootElement = document.getDocumentElement();
        NodeList records1 = rootElement.getElementsByTagNameNS("*", "record");
        NodeList records2 = rootElement.getElementsByTagNameNS("http://foo", "record");
        NodeList records3 = rootElement.getElementsByTagName("foo:record");
        System.out.printf("%d records1 found.\n", records1.getLength());
        System.out.printf("%d records2 found.\n", records2.getLength());
        System.out.printf("%d records3 found.\n", records3.getLength());
    }
}

印刷品:

0 records1 found.
0 records2 found.
1 records3 found.

共 (1) 个答案

  1. # 1 楼答案

    您需要一个名称空间感知解析器By default,JDK解析器不知道名称空间

    将代码更改为如下所示:

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);