簡體   English   中英

Xpath不區分大小寫的表達式,用於從XML獲取屬性

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM