简体   繁体   English

简单的XML框架:基于属性值的XPath匹配

[英]SImple XML Framework: XPath matching based on attribute value

Given XML like this: 给定这样的XML:

...
<Sport SportId="1">
    <Name language="en">Soccer</Name>
    <Name language="fi">Jalkapallo</Name>       
     ...    
</Sport>
...

How can I, using the Simple XML Framework , read the two values into fields in a Java class? 我如何使用Simple XML Framework将两个值读入Java类的字段? (The <Sport> element is already correctly mapped to the corresponding class.) <Sport>元素已正确映射到相应的类。)

public class Sport {    
    ...
    String nameEn;
    String nameFi;
    ...
}

I've tried approaches like: 我尝试过这样的方法:

@Element(name = "Name")
@Path("Name[@language='en']")
String nameEn;

But the parsing fails with: 但是解析失败了:

Exception in thread "main" org.simpleframework.xml.core.PathException: 
  Invalid index for path '[@language='en']' in field 'nameEn'

Also, omitting @Element like this: 另外,省略@Element是这样的:

@Path("Name[@language='en']")
String nameEn;

...parsing doesn't crash, but nameEn value stays null. ...解析不会崩溃,但nameEn值保持为null。

I'd like the matching to be based on the language attribute (instead of ordering), but I'm wondering if that's possible (maybe XPath support in Simple Framework is limited?). 我希望匹配基于语言属性 (而不是排序),但我想知道这是否可能(简单框架中的XPath支持是否有限?)。

Have you tried getting the text of the element explicitly? 您是否尝试过显式获取元素的文本? ie Name[@language='en']/text() Name[@language='en']/text()

Your Xpath is selecting the element , not the text of the element, which can cause some XML engines to choke. 您的Xpath正在选择元素 ,而不是元素文本 ,这可能导致某些XML引擎窒息。

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

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