简体   繁体   English

xpathGetString总是返回空字符串

[英]xpathGetString always returning empty string

I am trying to read attribute from CustomXmlPart using xpathGetString 我正在尝试使用xpathGetString从CustomXmlPart读取属性

String abcd = lc_CustomXmlPart.xpathGetString( "/Contract/Currency[1]/@Code", "" );
System.out.println( abcd );

But it always returns empty string. 但是它总是返回空字符串。

Xml looks like this: Xml看起来像这样:

<Contract xmlns="http://abc.123.cz" TypeCode="HO" IssueDate="2017-02-11">
    <Currency Code="EUR" Name="Default" PrintCode="€"></Currency>
</Contract>

Can someone please tell me what am I doing wrong? 有人可以告诉我我在做什么错吗?

The XML defines a default namespace ( xmlns ) and you're trying to access its nodes without specifying that namespace. XML定义了默认名称空间( xmlns ),并且您尝试访问其节点而不指定该名称空间。

You can change your XPath to access nodes of any namespace : 您可以更改XPath来访问任何名称空间的节点:

  • in XPath 1.0 : /*[local-name()='Contract']/*[local-name()='Currency'][1]/@Code 在XPath 1.0中: /*[local-name()='Contract']/*[local-name()='Currency'][1]/@Code

  • in XPath 2.0 : /*:Contract/*:Currency/@Code 在XPath 2.0中: /*:Contract/*:Currency/@Code

But it would be best to specify it : 但是最好指定它:

String abcd = lc_CustomXmlPart.xpathGetString( "/abc:Contract/abc:Currency[1]/@Code", "xmlns:abc=\"http://abc.123.cz\"" );

I'm not sure about the exact syntax, check your API documentation ; 我不确定确切的语法,请查看您的API文档; what I'm sure about is that there is a way to specify prefix mappings which you'll be able to use in your XPath. 我确定的是,有一种方法可以指定前缀映射,您可以在XPath中使用它。

Note that there might be a way to specify a default namespace for your XPath query which would lead to the same result (selecting the node of the specific namespace) without having to modify your XPath. 请注意,可能有一种方法可以为XPath查询指定默认名称空间,这将导致相同的结果(选择特定名称空间的节点),而无需修改XPath。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM