[英]why getNamespaceURI() always return null?
為什么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
,我在哪里錯?
從這個 ,你需要設置一個標志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...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.