Search code examples
javaxmlxml-parsingxml-serializationsimple-framework

Java, SimpleXML with different prefixes in one Path


I have a XML file which has that kind of structure:

<a:root>
    <a:body>
      <b:do_action>
        <b:do_input>
           <request>
              <!-- There are a lot of primitive elements -->
           </request>
        </b:do_input>
      </b:do_action>
    </a:body>
</a:root>

I'm trying to parse this XML by using SimpleXML:

public class Request {
   // There are a lot of defined primitive elements
}

@Root(name = "root")
@Namespace(prefix = "a")
public class Root {

   @Path("a:body/b:do_action/b:do_input")
   @Element(name = "request")
   public Request request;
}

When I instantiate my object and want to show it as string, I get this error message:

org.simpleframework.xml.core.ElementException: Namespace prefix 'b' in class Request is not in scope

How to deal with paths, which have different prefixes?


Solution

  • Since you use two different namespaces, you should declare both of them:

    @Root(name = "root")
    @NamespaceList({
        @Namespace(prefix = "a" , reference="ref_a"), 
        @Namespace(prefix = "b", reference="ref_b")})
    public class Root {
    }
    

    Hope it helps.