Home>
Using JAXB, XML obtained from RSS is converted to an object using the unmarshal method.
Since XML obtained from RSS has a namespace, the namespace is also defined for the object.
With marshal method from the converted object,
I would like to generate XML again.
I don't know how to generate XML without a namespace.
Is it impossible to separate between marshal and unmarshal?
I would appreciate it if you could tell me.

// Object to convert from XML
//Root.java
@XmlRootElement (name = "RDF")
public class Root implements Serializable {

    List<Child>child;
    @XmlElement (name = "item", namespace = "http://purl.org/rss/1.0/")
    public List<Child>getChild () {
        return child;
    }
    public void setChild (List<Child>child) {
        this.child = child;
    }
}
// Object to convert from XML
//Child.java
@XmlRootElement (name = "item")
public class Child implements Serializable {
    String title;
    @XmlElement (name = "title", namespace = "http://purl.org/rss/1.0/")
    public String getTitle () {
        return title;
    }
    public void setTitle (String title) {
        this.title = title;
    }
}
  • Answer # 1

    How about this?

    Reference: java-How to marshal without a namespace?-Stack Overflow

    package jaxb;
    import javax.xml.bind.JAXB;
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.JAXBException;
    import javax.xml.bind.Marshaller;
    import javax.xml.namespace.NamespaceContext;
    import javax.xml.stream.XMLOutputFactory;
    import javax.xml.stream.XMLStreamException;
    import javax.xml.stream.XMLStreamWriter;
    import java.io.StringWriter;
    import java.net.URI;
    import java.util.Iterator;
    public final class Main {
        public static void main (String [] args) throws XMLStreamException, JAXBException {
            Root root = JAXB.unmarshal (URI.create ("https://www.nttdocomo.co.jp/info/rss/whatsnew.rdf"), Root.class);
            StringWriter writer = new StringWriter ();
            XMLStreamWriter xmlWriter = XMLOutputFactory.newFactory (). CreateXMLStreamWriter (writer);
            xmlWriter.setNamespaceContext (new NamespaceContext () {
                public Iterator getPrefixes (String namespaceURI) {
                    return null;
                }
                public String getPrefix (String namespaceURI) {
                    return "";
                }
                public String getNamespaceURI (String prefix) {
                    return null;
                }
            });
            // No namespace
            JAXBContext context = JAXBContext.newInstance (Root.class);
            Marshaller marshaller = context.createMarshaller ();
            marshaller.marshal (root, xmlWriter);
            System.out.println (writer.toString ());
        }
    }