【问题标题】:Use netty for parsing XML strings使用 netty 解析 XML 字符串
【发布时间】:2018-04-11 07:16:11
【问题描述】:

我正在通过 TCP 以标准 xml 格式获取消息,我正在通过我的 netty 客户端收听这些消息。应该如何编写我的管道,以便我可以解析以 <abc>....</abc> 开头和结尾的字符串?

我猜应该有一个字符串解码器和另一个处理从 TCP 流解析 XML 的自定义处理程序(netty 定义或其他方式)。

类似于以下内容?

public Bootstrap createBootstrap(final Bootstrap b, EventLoopGroup eventLoop) {
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    ReconnectionClient reconnectionClient = new ReconnectionClient(this);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(reconnectionClient);
            pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));             
            pipeline.addLast(new ClientHandler()); // deals with String parsing                
        }
    });

    // Use command line arguments to pass the socket
    b.connect(serverIP, serverPort).addListener(new ConnectionListener(this));
    return b;
}

我的问题的第二部分是如何解析通过 TCP 传输的单个 XML 字符串?例如,应该在 ClientHandler() 中编写什么代码来实现此功能?

【问题讨论】:

    标签: java xml tcp netty


    【解决方案1】:

    如果您只想使用 netty 解码 XML,您可以使用内置 XML-decoder(此处理程序不需要 StringDecoder)。如果您想在&lt;abc&gt; 标记之后开始处理 XML 文档,您可以简单地等待名称为abc 的XmlElementStart 对象。关闭标签也是如此,但带有 XmlElementEnd 对象。

    【讨论】:

      猜你喜欢
      • 2010-12-23
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-12
      • 1970-01-01
      • 2016-04-25
      相关资源
      最近更新 更多