Java XmlHttpContent序列化程序按字母顺序排序文件
我需要严格遵守xml文档中元素的顺序。如果我使用XmlHttpContent序列化程序来形成xml内容,字段将按字母顺序排序Java XmlHttpContent序列化程序按字母顺序排序文件,java,xml,Java,Xml,我需要严格遵守xml文档中元素的顺序。如果我使用XmlHttpContent序列化程序来形成xml内容,字段将按字母顺序排序 有什么方法可以显式地指定xml中元素的顺序吗?还是有其他方法可以使用xml正文创建和发布http请求?我知道这个答案并不理想,但最近我在尝试使用http客户端库序列化为xml时遇到了这个问题。我发现有效的解决方案是让我的DTO类提供一种方法,将它们转换为某种类型的排序映射 在我的例子中,这是一个ImmutableMap,我也在使用它,但是任何具有可控顺序的映射都可以。基本
有什么方法可以显式地指定xml中元素的顺序吗?还是有其他方法可以使用xml正文创建和发布http请求?我知道这个答案并不理想,但最近我在尝试使用http客户端库序列化为xml时遇到了这个问题。我发现有效的解决方案是让我的DTO类提供一种方法,将它们转换为某种类型的排序映射 在我的例子中,这是一个
ImmutableMap
,我也在使用它,但是任何具有可控顺序的映射都可以。基本思想是使用java对象来构造数据,但是当需要序列化它们时,您可以将映射序列化
public interface OrderedXml {
ImmutableMap<String, Object> toOrderedMap();
}
public class Parent implements OrderedXml {
@Key("First") String first;
@Key("Second") String second;
@Key("Child") Child third;
@Override
public ImmutableMap<String, Object> toOrderedMap() {
return ImmutableMap.of(
// the order of elements in this map will be the order they are serialised
"First", first,
"Second", second,
"Child", third.toOrderedMap()
);
}
}
public class Child implements OrderedXml {
@Key("@param1") String param1;
@Key("@param2") String param2;
@Key("text()") String value;
@Override
public ImmutableMap<String, Object> toOrderedMap() {
return ImmutableMap.of(
// the same goes for attributes, these will appear in this order
"@param1", param1,
"@param2", param2,
"text()", value
);
}
}
public class Main {
public static void main(String[] args) {
// make the objects
Parent parent = new Parent();
parent.first = "Hello";
parent.second = "World";
parent.child = new Child();
parent.child.param1 = "p1";
parent.child.param2 = "p2";
parent.child.value = "This is a child";
// serialise the object to xml
String xml = new XmlNamespaceDictionary()
.toStringOf("Parent", parent.toOrderedXml()); // the important part
System.out.println(xml); // should have the correct order
}
}
公共接口OrderedXml{
ImmutableMap toOrderedMap();
}
公共类父级实现OrderedXml{
@键(“第一”)字符串优先;
@键(“第二”)字符串第二;
@关键(“儿童”)儿童第三;
@凌驾
公共ImmutableMap toOrderedMap(){
返回ImmutableMap.of(
//此映射中元素的顺序将与它们序列化的顺序相同
“第一”,第一,
第二,第二,,
“Child”,第三个。toOrderedMap()
);
}
}
公共类子级实现OrderedXml{
@键(“@param1”)字符串param1;
@键(“@param2”)字符串param2;
@键(“text()”)字符串值;
@凌驾
公共ImmutableMap toOrderedMap(){
返回ImmutableMap.of(
//属性也是如此,它们将按以下顺序显示
“@param1”,param1,
“@param2”,param2,
“text()”,值
);
}
}
公共班机{
公共静态void main(字符串[]args){
//制作对象
父项=新父项();
parent.first=“你好”;
parent.second=“World”;
parent.child=新的子对象();
parent.child.param1=“p1”;
parent.child.param2=“p2”;
parent.child.value=“这是一个子项”;
//将对象序列化为xml
字符串xml=新的XmlNamespaceDictionary()
.toStringOf(“Parent”,Parent.toOrderedXml());//重要部分
System.out.println(xml);//应具有正确的顺序
}
}
我知道这个解决方案并不理想,但至少您可以重用
toOrderedXml
来创建一个漂亮的toString
:-)。元素和属性的顺序由XML规范保证,如果您需要特定的顺序,您需要提供一个可以对解析结果进行排序的顺序。