我有一个 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() 会给出没有命名空间的节点名称。那么我的情况出了什么问题?
最佳答案
您需要先将文档生成器工厂设置为可识别 namespace 。然后 getLocalName()
将开始返回非空值。
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
docBuilder.setNamespaceAware(true); // <=== here
Document document = docBuilder.parse(new File("C:\\Users\\DadMadhR\\Desktop\\temp\\EDR_D3A0327.XML"));
关于java - 如何在java中获取没有命名空间的XML节点名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35763906/