gpt4 book ai didi

java - 为什么 getNamespaceURI() 总是返回 null?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:45:27 26 4
gpt4 key购买 nike

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

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>

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

最佳答案

来自 this ,你需要设置一个标志factory.setNamespaceAware(true),像这样:

    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...

关于java - 为什么 getNamespaceURI() 总是返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27715183/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com