简体   繁体   English

JAVA / JAXB在解组时应用多个名称空间

[英]JAVA/JAXB Applying multiple namespaces when unmarshalling

I have an xml and I am trying to unmarshal. 我有一个xml,我正试图解组。 It fails because it is missing the require namespaces. 它失败,因为它缺少require命名空间。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<tracks>
  <tracklet><sightings/></tracklet>
<tracks>

Needs to become: 需要成为:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns3:tracks xmlns:ns3="http://www.mytrack.com/TRACK" xmlns:xmime="http://www.w3.org/2005/05/xmlmime">
  <tracklet><sightings/></tracklet>
</ns3:tracks>

This example of NamespaceFilter only does one namespace. NamespaceFilter的此示例仅执行一个名称空间。 I need one that will append two namespaces. 我需要一个将追加两个名称空间的程序。

public class NamespaceFilter extends XMLFilterImpl {

    private static final String NAMESPACE = "http://www.example.com/customer";

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(NAMESPACE, localName, qName);
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
        super.startElement(NAMESPACE, localName, qName, atts);
    }
}

The NamespaceFilter in your question doesn't "add" the namespace declaration, it adjusts the namespace portion of an elements qualified name. 您问题中的NamespaceFilter不会“添加”名称空间声明,它会调整元素限定名称的名称空间部分。

For your XML you just need to adjust the NamespaceFilter so that it only returns the namespace when the qname parameter is tracks . 对于您的XML,您只需要调整NamespaceFilter ,使其仅在qname参数为tracks时返回名称空间。

@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
    if("tracks".equals(qname) {
        super.startElement(NAMESPACE, localName, qName, atts);
    } else {
        super.startElement(uri, localName, qName, atts);
    }
}

Here is the link to my blog post where the NamespaceFilter came from: 这是我的博客文章NamespaceFilter来源的链接:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM