转换XML => JSON =>基于XSD架构的XML [英] Conversion XML => JSON => XML based on a XSD Schema

查看:161
本文介绍了转换XML => JSON =>基于XSD架构的XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个主题上看到了很多话题,但没有一个答案. 实际上是否有一个JAVA库可以使用XSD架构进行XML => JSON => XML的转换,从而更好地处理XML中单个元素的问题.

I saw lots of threads on this topic but not one with an answer. Is there actually a JAVA library which can make a conversion XML => JSON => XML using an XSD Schema to better handle the problematic of single element in XML.

(XML中的单个元素可以是数组或单个对象,具体取决于XSD架构)

(a single element in XML can be an array or a single object depending of the XSD schema)

XML示例:

    <root><person><name>test</name></person></root>

JSON可以是:

    {"root": [{"person": [{"name": "test"}]}]}

或带有对象而不是数组的任何东西:

or anything with object instead of array :

    {"root": {"person": {"name": "test"}}}

但是使用XSD,我们可以从maxoccurs参数中知道root是唯一的,person是一个数组,而name是唯一的,因此良好的转换应该是:

But with XSD we would know from the maxoccurs parameters that root is unique, person is an array and name is unique, so the good transformation would be :

    {"root": {"person": 
        [{"name": "foofdo"}]
    }}

提前谢谢

推荐答案

如果您使用的是 Java 8 或更高版本,则应签出我的开源库:

If you are using Java 8 or later, you should check out my open source library: unXml. unXml basically maps from Xpaths to Json-attributes.

可以在 Maven Central 中使用.

示例

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.nerdforge.unxml.factory.ParsingFactory;
import com.nerdforge.unxml.parsers.Parser;
import org.w3c.dom.Document;

public class Parser {
  public ObjectNode parseXml(String xml){
    Parsing parsing = ParsingFactory.getInstance().create();
    Document document = parsing.xml().document(xml);

    Parser<ObjectNode> parser = parsing.obj("/root/person")
        .attribute("name")
        .build();

    ObjectNode result = parser.apply(document);
    return result;
  }
}

它将返回 Jackson ObjectNode,并带有以下json:

It will return a Jackson ObjectNode, with the following json:

{"name":"test"}

数组示例

或者,如果您有多个person,则可以让它返回 Jackson ArrayNode

Alternativly if you have multiple person, you can have it return a Jackson ArrayNode

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.nerdforge.unxml.factory.ParsingFactory;
import com.nerdforge.unxml.parsers.Parser;
import org.w3c.dom.Document;

public class Parser {
  public ArrayNode parseXml(String xml){
    Parsing parsing = ParsingFactory.getInstance().create();
    Document document = parsing.xml().document(xml);

    Parser<ArrayNode> parser = parsing.arr("/root/person")
        .attribute("name")
        .build();

    ArrayNode result = parser.apply(document);
    return result;
  }
}

这将为您的输入创建以下json:

This will create the following json for your input:

[{"name":"test"}]

这篇关于转换XML => JSON =>基于XSD架构的XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆