【发布时间】:2019-03-27 01:00:05
【问题描述】:
我有一个 xml 文件,其中包含如下所示的数据:
....
<ems:MessageInformation>
<ecs:MessageID>2147321820</ecs:MessageID>
<ecs:MessageTimeStamp>2016-01-01T04:38:33</ecs:MessageTimeStamp>
<ecs:SendingSystem>LD</ecs:SendingSystem>
<ecs:ReceivingSystem>CH</ecs:ReceivingSystem>
<ecs:ServicingFipsCountyCode>037</ecs:ServicingFipsCountyCode>
<ecs:Environment>UGS-D8UACS02</ecs:Environment>
</ems:MessageInformation>
....
还有许多其他节点。所有节点都有命名空间,如 ecs、tns、ems 等。我正在使用以下代码部分来提取所有没有命名空间的节点名称。
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, TransformerException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("C:\\Users\\DadMadhR\\Desktop\\temp\\EDR_D3A0327.XML"));
NodeList nodeList = document.getElementsByTagName("*");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
//System.out.println(node.getNodeName());
System.out.println(node.getLocalName());
}
}
但是当我执行这段代码时,它会为单个节点打印 null。谁能告诉我我在这里做错了什么?
我在互联网上阅读,我知道 node.getLocalName() 将给出没有命名空间的节点名称。那么在我的情况下有什么问题?
【问题讨论】:
-
对于除 ELEMENT_NODE 和 ATTRIBUTE_NODE 以外的任何类型的节点以及使用 DOM 级别 1 方法(例如 Document.createElement())创建的节点,这始终为 null
-
最好先检查节点类型,然后使用方法