My XML in test.xml
:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<record>
<req1:name>john</req1:name>
<age req:valid="f">57</age>
</record>
My Java code:
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(getClass().getClassLoader().getResourceAsStream("test.xml"));
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new DOMSource(document),result);
System.out.println(writer.toString());
When running the transformer.transform
will throw an exception
Namespace for prefix 'req' has not been declared
If I remove the req: prefix from the attribute it's working. There is no exception for the req1 prefix. The exception only appears for attributes.
Is there a way disable that kind of validation ?
I tried with
documentBuilderFactory.setValidating(false);
documentBuilderFactory.setNamespaceAware(false);
but it changes nothing.
namespace needs to be declared
try
<record xmlns:req="http://your-ns-url">
<!-- ... -->
</record>
Edit:
If you just want to get rid of the exception add the namspace to the doc root before transforming to string
Element documentElement = document.getDocumentElement();
// Add name space to root element as attribute
documentElement.setAttribute("xmlns:req", "http://you_name_space");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.