JAXB - 在SpringBoot中将带有命名空间的XML发送到REST控制器

时间:2017-09-30 05:55:44

标签: java xml spring-boot namespaces jaxb

我正在将xml发布到我的springboot应用程序并将其接收到Pojo Jaxb并返回响应。我能够成功地做到这一点,但是如果我通过命名空间传递xml我得到响应代码为406而响应正文为无内容。我尝试了各种方法在我的Pojo中添加命名空间,甚至尝试在package-info中添加它,但我无法找到让它工作的方法,请建议。下面是一个简单的xml没有命名空间的工作示例

Pojo Employee.java

@XmlRootElement(name = "Employee")
public class Employee {  
    private int id;  
    private String name;  
    private float salary;  

    public Employee() {}  
    public Employee(int id, String name, float salary) {  
        super();  
        this.id = id;  
        this.name = name;  
        this.salary = salary;  
    }  
    @XmlAttribute  
    public int getId() {  
        return id;  
    }  
    public void setId(int id) {  
        this.id = id;  
    }  
    @XmlElement  //(namespace="http://www.example.org/property")
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    @XmlElement  
    public float getSalary() {  
        return salary;  
    }  
    public void setSalary(float salary) {  
         this.salary = salary;  
    }  
}

下面是我的Controller方法,它通过POJO从xml获取值

@RequestMapping(value = { "/myURL" }, method = RequestMethod.POST, consumes = { "application/xml" })
public ResponseEntity<?> postMethodXMLreturnXML(@RequestBody Employee list) {  
    try {
        Employee FirstValue=list;
        System.out.println("SOP : post Method started . Name " + FirstValue.getName());         
        return new ResponseEntity<Object>(Employee , HttpStatus.CREATED);
    } catch (Exception e) {
        e.printStackTrace();
        return (new ResponseEntity<String>(ErrorCodes.SERVER_ERROR.getDescription(),
                HttpStatus.INTERNAL_SERVER_ERROR));
    }
}

下面是我发布到此的xml,并获得带有效响应代码和响应消息的所需输出

输入帖子xml

<?xml version="1.0"?>
<Employee>
  <id>1</id>
  <name>myName</name>
  <salary>1.1</salary>
</Employee>

但我现在想要传递下面的xml,当我将xml传递给此代码时,我得到响应代码406而没有内容,尝试在pojo中添加命名空间甚至尝试添加代码到包信息,请咨询 提前致谢

<?xml version="1.0"?>
<Employee>
  <myns:id>1</myns:id>
  <myns:name>myName</myns:name>
  <myns:salary>1.1</myns:salary>
</Employee>

1 个答案:

答案 0 :(得分:1)

XML使用名称空间前缀,但名称空间本身未在Employee的开始标记中定义。

class MultipleObjectMixin(ContextMixin):

    def get_paginate_by(self, queryset):
        """
        Get the number of items to paginate by, or ``None`` for no pagination.
        """
        return self.paginate_by

还要将命名空间添加到每个XML元素。

<?xml version="1.0"?>
<Employee xmlns:myns="http://example/a/b/c">
  <myns:id>1</myns:id>
  <myns:name>myName</myns:name>
  <myns:salary>1.1</myns:salary>
</Employee>