![](/img/trans.png)
[英]Get Attributes of the Root element in XML using xpath query expression in Java
[英]Xpath Case insensitive expression to get attributes from an XML
我正在閱讀一些XML
文件,並使用Xpath
的幫助使用一些預定義的路徑提取一些值
路徑看起來像這樣:
Comprobante/@Fecha
例如,上面的路徑將用於提取屬性@Fecha
,該文件看起來像這樣:
<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" Fecha="2017-10-25T19:13:19">
</cfdi:Comprobante>
這是一個用於獲取數據的代碼示例,在這種情況下,我將獲得attribue @Fecha
的值。
代碼示例
File inputFile = new File(file);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xPath.compile("Comprobante/@Fecha")
String names = (String) expr.evaluate(doc, XPathConstants.STRING);
據我所知,XML文件區分大小寫,我一直在閱讀的文件總是帶有字母F
大寫的@Fecha
,但最近我收到了很多帶@fecha
而不是@Fecha
的文件,除了通常的文件@Fecha
,我無法控制文件的寫入方式,所以我需要找到解決此問題的方法,因為我的代碼在應用於具有@fecha
的文件時返回null
帶有@fecha
的文件@fecha
:
<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3" fecha="2017-10-25T19:13:19">
</cfdi:Comprobante>
我可以做一個if
語句並檢查Im得到的值是否為empty
,然后再次檢查但是使用@fecha
而不是@Fecha
,如下所示:
File inputFile = new File(file);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xPath.compile("Comprobante/@Fecha")
String names = (String) expr.evaluate(doc, XPathConstants.STRING);
if(names.isEmpty()){
XPathExpression expr = xPath.compile("Comprobante/@fecha")
String names = (String) expr.evaluate(doc, XPathConstants.STRING);
}
但我想知道是否有辦法用Xpath Expression
來獲取@Fecha
的值而不管字母F
的大小,而不是IF
表達式,我發現我可以使用函數translate
來做到這一點, 就像是:
translate(@Fecha, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')
但我似乎無法使其發揮作用。
你的XPath,
translate(@Fecha, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')
將@Fecha
屬性值轉換為小寫。
這個XPath 1.0 ,
Comprobante/@*[translate(local-name(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyz')
= 'fecha']
選擇Comprobante
的屬性,其名稱小寫為fecha
。
或者在XPath 2.0中更簡潔:
Comprobante/@*[lower-case(local-name()) = 'fecha']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.