本文介绍了为什么getNamespaceURI()总是返回null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么getNamespaceURI()总是返回null?printNSInfo方法有什么问题

why getNamespaceURI() always return null? what's wrong in printNSInfo method

public static void main(String[] args) {
    Document input = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(args[0]);
    Element root = input.getDocumentElement();
    printNSInfo(root);
}

private static void printNSInfo(Node node) {
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        if (node.getNamespaceURI() != null) {
            System.out.println("Element Name:" + node.getNodeName());
            System.out.println("Local Name:" + node.getLocalName());
            System.out.println("Namespace Prefix:" + node.getPrefix());
            System.out.println("Namespace Uri:" + node.getNamespaceURI());
            System.out.println("---------------");
        }
        if (node.hasAttributes()) {
            NamedNodeMap map = node.getAttributes();
            int len = map.getLength();
            for (int i = 0; i < len; i++) {
                Node attr = map.item(i);
                if (attr.getNamespaceURI() != null) {
                    printNSInfo(attr);
                }
            }
        }
        Node child = node.getFirstChild();
        System.out.println(child);
        while (child != null) {
            printNSInfo(child);
            child = child.getNextSibling();
        }
    } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        System.out.println("Attribute Name:" + node.getNodeName());
        System.out.println("Local Name:" + node.getLocalName());
        System.out.println("Namespace Prefix:" + node.getPrefix());
        System.out.println("Namespace Uri:" + node.getNamespaceURI());
        System.out.println("---------------");
    }
}

输入的xml文件为:

<a:NormalExample xmlns:a="http://sonormal.org/" xmlns:b="http://stillnormal.org/">
    <a:AnElement b:anAttribute="text"> </a:AnElement>
</a:NormalExample>

当我在日食中调试时, node.getNamespaceURI()总是返回 null ,我在哪里错了?

when I debug in eclipse, node.getNamespaceURI() always return null, where am I wrong?

推荐答案

来自,您需要设置一个标志 factory.setNamespaceAware(true),如下所示:

From this, you need to set a flag factory.setNamespaceAware(true), like this:

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document input = builder.parse(args[0]);

    Element root = input.getDocumentElement();
    printNSInfo(root);

输出为:

Element Name:a:NormalExample
Local Name:NormalExample
Namespace Prefix:a
Namespace Uri:http://sonormal.org/
---------------
...continue...

这篇关于为什么getNamespaceURI()总是返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 01:47