gpt4 book ai didi

java - 如何使用 Path 解析 ElementList?

转载 作者:行者123 更新时间:2023-11-30 09:11:54 26 4
gpt4 key购买 nike

这是我想用 SimpleFramework 反序列化的 XML 片段:

<rs><r>
<id>23</id>
<bar>blargh</bar>
<c><v>value 1</v></c>
<c><v>value 2</v></c>
<c><v>yet another value</v></c>
<c><v>moar value</v></c>
</r></rs>

我最终想要的是一个包含所有元素内容的 ElementList。我在想象这样的事情:

@Root(strict=false)
public static class Foo {
@Element(name="id")
public int id;
@Element(name="bar")
public String info;
@Path("c")
@ElementList(entry="v", inline=true, required=false, empty = false)
public List<String> values;
}

我正在尝试做的是越过“c”元素,直接进入列表中每个成员的“v”元素。上面的代码没有这样做。我希望将 @Path("c") 语句应用于列表中的每个元素,但我不知道如何实现。

最佳答案

我在这里看到两个问题:

  1. <rs><r>...</r></rs>root 元素的嵌套标签(不是确定 @Path可以处理这个......)
  2. 每个条目的两个标签 ( <c><v>...</v></c> ) 是不可能的通过@ElementList注释(和 @Path 不能为每个条目设置)

作为解决方案,您可以编写两个包装器类:

  • 一个,包裹根节点
  • 另一个,放在列表中,将每个条目包装起来

下面是实现:

FooWrapper

这个类包装了一个 Foo类(class);你通过包装器和带有实际对象的 r-tag 获得 rs-tag。

@Root(name = "rs")
public class FooWrapper
{
@Element(name = "r", required = true)
private Foo f;


public FooWrapper(Foo f) // Required just in case you want to serialize this object
{
this.f = f;
}

FooWrapper() { } // At least a default ctor is required for deserialization
}

Foo

这里没有什么特别的。只有列表条目的类型更改为 EntryWrapper .

@Root(strict = false)
public class Foo /* A */
{
@Element(name = "id")
public int id; /* B */
@Element(name="bar")
public String info;
@ElementList(entry="c", inline=true, required=false, empty = false)
public List<EntryWrapper> values; // Replacing the String with the EntryWrapper

// ...
}
  • /* A */ :在您的代码中,这是 static同样,我刚刚删除了它,因为我将它放入了自己的类文件中。
  • /* B */ : 更好:封装字段,使它们成为private并编写 getter/setter。

EntryWrapper

列表中的每个条目都被包装到这样一个包装器对象中。顺便提一句。无需公开此类 public .

public class EntryWrapper
{
@Element(name = "v")
private String value;


public EntryWrapper(String value)
{
this.value = value;
}

EntryWrapper() { } // Once again, at least one default ctor is required for deserialization

// ...
}

关于java - 如何使用 Path 解析 ElementList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21887049/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com