dom4j selectSingleNode return 空值
dom4j selectSingleNode return null value
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");
但它不起作用,它 returns 无效。
我应该如何更改代码?
提前致谢
干杯
更新
所以这是关于命名空间的问题。
我正在尝试这样的事情
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/empty 值
我想我遗漏了一些关于命名空间的东西...
解决方案
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));
不仅节点的本地名称发生了变化,命名空间也发生了变化。您需要将前缀绑定到命名空间,然后 select 使用该前缀。
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");
但它不起作用,它 returns 无效。 我应该如何更改代码?
提前致谢
干杯
更新
所以这是关于命名空间的问题。 我正在尝试这样的事情
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/empty 值
我想我遗漏了一些关于命名空间的东西...
解决方案
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));
不仅节点的本地名称发生了变化,命名空间也发生了变化。您需要将前缀绑定到命名空间,然后 select 使用该前缀。