How to generate xml via SAXBuilder with namespace?

millka_15 :

xml as String:

String inputStr = "<f:table f:id=\"1\">\n" +
                "  <f:name>African Coffee Table</f:name>\n" +
                "  <f:width>80</f:width>\n" +
                "  <f:length>120</f:length>\n" +
                "</f:table>";

I want to generate this xml to jdom document :

StringReader stringReader = new StringReader(inputStr);
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(stringReader);

But the doc is null, and when I want to get root element, I get a NullPointerException.

How I can generate xml from string with namespace?

Sean Bright :

You should be getting a org.jdom2.input.JDOMParseException when you run that code. This is what I get:

org.jdom2.input.JDOMParseException: Error on line 1: The prefix "f" for element "f:table" is not bound.

So as I mentioned in comments, you need to provide a namespace URI for the f prefix, like this:

String inputStr = "<f:table f:id=\"1\" xmlns:f=\"http://millka_15.namespace\">\n" +

I've just used http://millka_15.namespace as a placeholder, I assume you know what the actual namespace URI should be.

The following code:

String inputStr = "<f:table f:id=\"1\" xmlns:f=\"http://millka_15.namespace\">\n" +
        "  <f:name>African Coffee Table</f:name>\n" +
        "  <f:width>80</f:width>\n" +
        "  <f:length>120</f:length>\n" +
        "</f:table>";

StringReader stringReader = new StringReader(inputStr);
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(stringReader);

System.out.println(doc);

Results in this output:

[Document:  No DOCTYPE declaration, Root is [Element: <f:table [Namespace: http://millka_15.namespace]/>]]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=108724&siteId=1