XStream:解析时 XML 层次结构崩溃

2024-01-29

我有一个 XML 文档(由 Adob​​e XFA 表单生成),其中包含如下数据:

<Position>
   <PositionBorder>
       <Title/>
       <StartDate/>
       <EndDate/>
   </PositionBorder>
</Position>

由于该文件是在其他地方定义的,因此我无法随意更改所获得的 XML 的格式。

在我的 Java 代码中,我创建了一个 Position 类,其中包含标题、开始日期和结束日期。

我的问题是,当我使用 XStream 解析文件时,它需要一个 PositionBorder 类来保存标题和日期。我想基本上忽略边框并将所有字段放入 Position 类中。

我真正想做的是使用像convertAnother 方法这样的方法来转换position 元素的子元素。我尝试这样做,但失败了,因为我的 PositionConverter 被调用以获取 PositionBorder (当我调用 ConvertAnother 时)。

有人知道如何在解析时处理 XML 结构的崩溃吗?


使用自定义转换器并不是非常困难。这是一个有点长的示例,但我希望它足够简单,足以让您了解需要执行的操作的要点:

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public final class ConverterTest {
    public static void main(String[] args) {
        XStream xstream = new XStream();
        xstream.autodetectAnnotations(true);
        xstream.registerConverter(new PositionConverter());

        final Position position = new Position();
        position.setTitle("The Title");
        position.setStartDate("The Start Date");
        position.setEndDate("The End Date");

        final String xml = xstream.toXML(position);
        System.out.println("Generated XML:");
        System.out.println(xml);

        final Position genPosition = (Position) xstream.fromXML(xml);
        System.out.println("Generated Position:");
        System.out.println("\tTitle: " + genPosition.getTitle());
        System.out.println("\tStart Date: " + genPosition.getStartDate());
        System.out.println("\tEnd Date: " + genPosition.getEndDate());
    }

    @XStreamAlias("Position")
    private static class Position {
        public String getEndDate() {
            return endDate;
        }

        public void setEndDate(String endDate) {
            this.endDate = endDate;
        }

        public String getStartDate() {
            return startDate;
        }

        public void setStartDate(String startDate) {
            this.startDate = startDate;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        private String title;
        private String startDate;
        private String endDate;
    }

    private static class PositionConverter implements Converter {
        public boolean canConvert(Class clazz) {
            return Position.class == clazz;
        }

        public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
            Position position = (Position)value;
            writer.startNode("PositionBorder");

            writer.startNode("Title");
            writer.setValue(position.getTitle());
            writer.endNode();

            writer.startNode("StartDate");
            writer.setValue(position.getStartDate());
            writer.endNode();

            writer.startNode("EndDate");
            writer.setValue(position.getEndDate());
            writer.endNode();

            writer.endNode();
        }

        public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
            Position position = new Position();
            // move it to <PositionBorder> tag.
            reader.moveDown();
            // now move it to <Title> tag.
            reader.moveDown();
            String title = reader.getValue();
            position.setTitle(title);
            reader.moveUp(); // moves back to <PositionBorder>

            reader.moveDown(); // should move down to <StartDate> tag
            String startDate = reader.getValue();
            position.setStartDate(startDate);
            reader.moveUp(); // move back to <PositionBorder>

            reader.moveDown(); // should move down to <EndDate> tag
            String endDate = reader.getValue();
            position.setEndDate(endDate);
            reader.moveUp(); // move back to <PositionBorder>


            return position;
        }
    }
}

尝试运行它,看看会发生什么。当然,您需要修改它以适合您自己的类型 - 我只是对 Position 的所有字段使用字符串(并且我确信您的 Position 类也不是嵌套的),但是从 String 转换约会(或其他什么)应该是相当微不足道的。

你需要关注的一件事(我可能没有明白)完全地在我的示例中)与您的 reader.moveDown() 和 reader.moveUp() 调用相匹配。 (而且,如果您要进行任何编组而不仅仅是解组——我不希望从您的问题中得到这一点——您也会希望匹配您的 writer.startNode() 和 writer.endNode() 调用.)这个例子可能不会造成任何问题,但我确信如果您正在做更大的事情或使用相同的 XStream 或 Converter 实例处理多个文件,它会引发问题。另外,如果您从无效位置尝试 reader.moveDown(),您将得到一个非常丑陋的异常 - 它应该非常明显。

我必须稍微尝试一下 moveUp/moveDown 方法才能将它们放在正确的位置,因此我确信您需要对其进行测试并进行调整,直到获得所需的内容。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

XStream:解析时 XML 层次结构崩溃 的相关文章

随机推荐

  • 调试 ASP.NET 应用程序时,如何在 Firefox 关闭时结束调试会话?

    我将把 Mozilla Firefox 设置为 net 应用程序的默认 Web 浏览器 问题是即使我关闭浏览器窗口 应用程序仍保持运行模式 和IE不太一样 由于某些原因我必须使用 Fire Fox 而不是 IE 当 Firefox 窗口关闭
  • Maven archetype 插件不允许 archetype-resources 中的 .resources 通过

    我怎样才能制作这样的资源 gitignore成为最终项目的一部分 创建原型archetype resources gitignore mvn install mvn archetype generate 生成的项目不包含 gitignore
  • scrapy项目加载器返回列表不是单个值

    我正在使用 scrapy 0 20 我想使用项目加载器 这是我的代码 l XPathItemLoader item MyItemClass response response l add value url response url l a
  • 无法从我的协议类调用委托方法

    我在一类中有一个协议 protocol DataStorageManager void saveFile end interface DataManager NSObject id
  • Boot 3 升级后错误响应正文发生更改

    我的项目中有以下控制器端点 GetMapping value id public FooDto findOne PathVariable Long id Foo model fooService findById id orElseThro
  • ImageFont 检测丢失的字形(Python Pillow)[重复]

    这个问题在这里已经有答案了 这是一个简短的example http pillow readthedocs io en 3 1 x reference ImageFont html from PIL import ImageFont Imag
  • 如何处理 Node.js 中的“read ETIMEDOUT”?

    我有一个使用 Node js 的发布 订阅模型将数据从一个客户端传输到另一个客户端 此外 服务器还记录收到的所有内容并将其发送给新客户端 但是 某些数据在传输时损坏 并且出现如下错误 Error with socket Error writ
  • R中的快速并行二分距离计算

    使用并行 Rcpp 后端计算 R 中二分距离最快的方法是什么 parallelDist是一个很棒的包 带有 cpp 后端并支持多线程 但不支持二分距离计算 据我所知 Using parallelDist 用于二分距离矩阵计算 除了 m1 m
  • 从 C# 在现有 IE 窗口的选项卡中启动 URL

    当 browserExe 指向 Firefox Safari 或 Chrome 时 以下代码将在现有浏览器窗口中打开链接 当指向 IEXPLORE EXE IE7 时 将打开一个新窗口 ProcessStartInfo pi new Pro
  • 如何在 Visual Studio Code 中禁用 PHP 验证?

    在 Windows 版本的 Visual Studio Code 版本 0 10 1 中打开任何 PHP 文件时 我收到消息 无法验证 php 文件 没有找到php程序 使用 php validate executablePath 设置来配
  • 在 PHP7 中本机分析多个脚本

    自 PHP 7 发布以来 现在不可能使用以下命令来分析整个脚本选择declare ticks 1 在你的基本文件中 然后使用register tick function 监视每个刻度 因为它不再遵循包含路径 根据提交的 PHP 错误http
  • 如何解决.NET Core包版本冲突

    我正在从 NET MVC 5 Web 应用程序迁移到 NET Core 2 2 Web API 项目以及五个 NET Standard 2 0 项目 所有项目都托管在一个解决方案下 我现在收到 28 个关于包冲突的警告 MSB3277 这些
  • 如何更改geom_point中的颜色或ggplot中的线条[重复]

    这个问题在这里已经有答案了 我有一个这样的数据 data lt structure list sample structure c 1L 1L 1L 1L 1L 1L 1L 1L 1L 1L 2L 2L 2L 2L 2L 2L 2L 2L
  • 重载或可选参数之间的性能差异?

    我想知道是否应该在 C 中使用可选参数 到目前为止 我总是重载方法 但可选参数也很好 更干净 代码更少 我在其他语言中使用它们 所以我在某种程度上也习惯了它们 有什么反对使用它们的吗 性能对我来说是第一个关键点 会掉吗 Example co
  • 如何保存 raphael 生成的 svg

    有没有办法将 raphael 生成的 SVG 保存为 svg 文件 请注意 它只需要在 Chrome 中工作 我想出了一个解决方案拉斐尔导出 https github com ElbertF Raphael Export 它给了我一个有效的
  • 更新已部署的 SSIS 包

    我有一个已部署的 SSIS 包 其中包含时间表和所有内容 现在 我对这个包进行了更改 我是否必须重新部署它 并再次为其设置计划 或者是否有办法让已部署的 SSIS 包更新为最新版本 是的 您需要将包重新部署到调度程序期望找到包的任何位置 但
  • 在 Tensorflow 2 中将梯度可视化为热图

    我正在研究通过引导反向传播生成热图的任务 我重写了原来的Relu并获得了每个参数的梯度 但是 我不确定下一步应该做什么 感谢您的帮助 谢谢你 这是我的代码 我首先使用 tf RegisterGradient GuidedRelu like
  • Python urlparse——提取不带子域的域名

    需要一种使用 Python urlparse 从 url 中提取不带子域的域名的方法 例如我想提取 google com 来自完整的网址 例如 http www google com 我能想到的最接近的urlparse is the net
  • 如何在Python中将JSON字符串转换为整数?

    如何将此 json 中的年份和 isbn 转换为整数 title The Notebook author Nicholas Sparks year 1996 isbn 0553816713 您可以简单地用相应的 int 值更新这些值 dat
  • XStream:解析时 XML 层次结构崩溃

    我有一个 XML 文档 由 Adob e XFA 表单生成 其中包含如下数据