【问题标题】:dom4j selectSingleNode return null valuedom4j selectSingleNode 返回空值
【发布时间】:2020-05-12 17:49:56
【问题描述】:

XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<INVOICE xmlns:xs="http://www.w3.org/2001/XMLSchema"
         xmlns:fo="http://www.w3.org/1999/XSL/Format">
   <HEADER>      
...

读取 xml 的我的(工作)代码:

File inputFile = new File(filepath.toString());
SAXReader reader = new SAXReader();
Document document = reader.read(inputFile);
Node node = document.selectSingleNode("//INVOICE/HEADER");

他们像这样更改了 xml 文件:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Invoice xmlns="http://com.spx/commerce/rasp/transform">
    <Header>
...

我(只是)更改了代码

Node node = document.selectSingleNode("//Invoice/Header");

但它不起作用,它返回null。 我应该如何更改代码?

提前致谢

干杯

更新

所以这是关于命名空间的问题。 我正在尝试这样的事情

Namespace ns = new Namespace("","http://com.spx/commerce/rasp/transform");
document.add(ns);
document.selectSingleNode("//Invoice/Header");

XPath xpath = DocumentHelper.createXPath( "//Invoice/Header");
Map<String, String> map = new HashMap<String, String>();
map.put("", "http://com.spx/commerce/rasp/transform");
xpath.setNamespaceURIs(map);
Element tagElement = ((Element)xpath.selectSingleNode(document));

但我仍然有 null/空值

我想我遗漏了一些关于命名空间的东西......

解决方案

HashMap map = new HashMap();
map.put("t", "http://com.spx/commerce/rasp/transform");                   
XPath xpath = DocumentHelper.createXPath( "//t:Invoice/t:Header");
xpath.setNamespaceURIs(map);
Element tagElement = ((Element)xpath.selectSingleNode(document));

【问题讨论】:

    标签: java xml dom4j


    【解决方案1】:

    不仅节点的本地名称发生了变化,命名空间也发生了变化。您需要将前缀绑定到命名空间并使用该前缀进行选择。

    【讨论】:

      猜你喜欢
      • 2021-10-14
      • 1970-01-01
      • 2023-03-07
      • 2020-10-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多