Strange error: Cannot read attribute: element has children or text
Closed this issue · 3 comments
I get "ERROR: 'ParseError at [row,col]:[1,33] Cannot read attribute: element has children or text" when I try to convert the following json to xml.
{
"test" :
{
"@TransTyp" : "0",
"Hdr" : {}
}
}
If I change it a little, everything is fine. These are converted without problem:
{
"test" :
{
"@TransType" : "0",
"Hdr" : {}
}
}
{
"test" :
{
"@TransTyp" : "0",
"child" : {}
}
}
Can you help me?
Thanks,
Marko
First input works for me, I get:
<?xml version='1.0' encoding='UTF-8'?>
<test TransTyp="0">
<Hdr/>
</test>
Can you attach code and input file to show the problem?
Sorry, the input json I provided was not correct, because I did some json processing in between. Here is the actual problem.
When I convert the following json, there is no problem.
{"test":{"@attr":"1", "child":"1"}}
But when I put child element first and attribute second, I get error. This does not work:
{"test":{"child":"1", "@attr":"1"}}
And my function for conversion.
private String xml2json(String xmlInput) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
StringReader inputReader = new StringReader(xmlInput);
try {
JsonXMLConfig config = new JsonXMLConfigBuilder().autoArray(true).autoPrimitive(true).prettyPrint(true).build();
XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(inputReader);
Source source = new StAXSource(reader);
XMLStreamWriter writer = new JsonXMLOutputFactory(config).createXMLStreamWriter(baos);
Result result = new StAXResult(writer);
TransformerFactory.newInstance().newTransformer().transform(source, result);
} catch (Exception ex) {
log.error("xml2json: " + ex.getMessage(), ex);
} finally {
try {
baos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return baos.toString();
}
Okay, the input is invalid because objects starting with "@" are interpreted as XML attributes and attributes must come before children or text content ("$"). This is implied by the way the StAX API is designed (all attributes are available after the start element has been read).