我有以下XML:
<?xml version="1.0" encoding="UTF-8"?>
<Lenders>
<ns:FinancialOrganization xmlns:ns="http://www.starstandard.org/STAR/5">
<ns:BusinessTypeCode>F</ns:BusinessTypeCode>
<ns:CompanyName>FIRST NIAGARA BANK</ns:CompanyName>
<ns:CompanyCode>1ST NIAGARA BANK</ns:CompanyCode>
<ns:PostalAddress>
<ns:LineOne>PO BOX 76</ns:LineOne>
<ns:LineTwo>HUDSON, NY 12534</ns:LineTwo>
<ns:CountryID>US</ns:CountryID>
<ns:Privacy>
<ns:PrivacyIndicator>false</ns:PrivacyIndicator>
</ns:Privacy>
</ns:PostalAddress>
<ns:LegalClassificationCode>NIAG</ns:LegalClassificationCode>
</ns:FinancialOrganization>
<ns:FinancialOrganization xmlns:ns="http://www.starstandard.org/STAR/5">
<ns:BusinessTypeCode>F</ns:BusinessTypeCode>
<ns:CompanyName>BALLSTON SPA NATIONAL BANK</ns:CompanyName>
<ns:CompanyCode>BALLSTON SPA FIN</ns:CompanyCode>
<ns:PostalAddress>
<ns:LineOne>87 FRONT STREET</ns:LineOne>
<ns:LineTwo>BALLSTON SPA, NY 12020</ns:LineTwo>
<ns:CityName>BALLSTON SPA</ns:CityName>
<ns:CountryID>US</ns:CountryID>
<ns:Postcode>12020</ns:Postcode>
<ns:StateOrProvinceCountrySub-DivisionID>NY</ns:StateOrProvinceCountrySub-DivisionID>
<ns:Privacy>
<ns:PrivacyIndicator>false</ns:PrivacyIndicator>
</ns:Privacy>
</ns:PostalAddress>
<ns:LegalClassificationCode>BSN</ns:LegalClassificationCode>
</ns:FinancialOrganization>
<ns:FinancialOrganization xmlns:ns="http://www.starstandard.org/STAR/5">
<ns:BusinessTypeCode>F</ns:BusinessTypeCode>
<ns:CompanyName>CAPITAL ONE AUTO FINANCE</ns:CompanyName>
<ns:CompanyCode>CAP</ns:CompanyCode>
<ns:PostalAddress>
<ns:LineOne>P.O.BOX 255605</ns:LineOne>
<ns:LineTwo>SACRAMENTO CA 95865-5587</ns:LineTwo>
<ns:CityName>SACRAMENTO</ns:CityName>
<ns:CountryID>US</ns:CountryID>
<ns:Postcode>958655587</ns:Postcode>
<ns:StateOrProvinceCountrySub-DivisionID>CA</ns:StateOrProvinceCountrySub-DivisionID>
<ns:Privacy>
<ns:PrivacyIndicator>false</ns:PrivacyIndicator>
</ns:Privacy>
</ns:PostalAddress>
<ns:LegalClassificationCode>CAP</ns:LegalClassificationCode>
</ns:FinancialOrganization>
</Lenders>
我尝试使用XPath来计算返回的项目数,然后获取单个元素。这是我的例子,没有返回正确的结果:
/Lenders/ns:FinancialOrganization[1]/ns:BusinessTypeCode
count(/Lenders/ns:FinancialOrganization/ns:BusinessTypeCode)
我对XPath很陌生但是这个特殊的挑战让我很难过。我正在使用W3c Xpath评估在线工具:
http://www.utilities-online.info/xpath/?save=7f748259-a214-4f1e-8872-6f6306199331-xpath
答案 0 :(得分:1)
最有可能的是,您使用的在线工具不支持XPath中的命名空间前缀。我试图从XML中删除前缀,例如这个元素:
<ns:FinancialOrganization xmlns:ns="http://www.starstandard.org/STAR/5">
变成了这个没有前缀的元素:
<FinancialOrganization xmlns:ns="http://www.starstandard.org/STAR/5">
然后这个XPath按预期返回3
:
count(/Lenders/FinancialOrganization/BusinessTypeCode)
在我使用多个支持XPath的.NET库的经验中,我们需要手动声明前缀到命名空间的URI映射,然后才能在XPath查询中使用该前缀。 It seems that the same applies in Java。