下面列出了怎么用org.json.XML的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Converting a JSON doc containing a named array of nested arrays to
* JSONObject, then XML.toString() should result in valid XML.
*/
@Test
public void shouldHandleNestedArraytoString() {
String xmlStr =
"{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+
"\"outer\":[[1], [2], [3]]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+
"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}";
JSONObject jsonObject = new JSONObject(xmlStr);
String finalStr = XML.toString(jsonObject);
JSONObject finalJsonObject = XML.toJSONObject(finalStr);
String expectedStr = "<addresses><address><name/><nocontent/>"+
"<outer><array>1</array></outer><outer><array>2</array>"+
"</outer><outer><array>3</array></outer>"+
"</address><xsi:noNamespaceSchemaLocation>test.xsd</xsi:noName"+
"spaceSchemaLocation><xmlns:xsi>http://www.w3.org/2001/XMLSche"+
"ma-instance</xmlns:xsi></addresses>";
JSONObject expectedJsonObject = XML.toJSONObject(expectedStr);
Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject);
}
/**
* JSONObject with NULL value, to XML.toString()
*/
@Test
public void shouldHandleNullNodeValue()
{
JSONObject inputJSON = new JSONObject();
inputJSON.put("nullValue", JSONObject.NULL);
// This is a possible preferred result
// String expectedXML = "<nullValue/>";
/**
* This is the current behavior. JSONObject.NULL is emitted as
* the string, "null".
*/
String actualXML = "<nullValue>null</nullValue>";
String resultXML = XML.toString(inputJSON);
assertEquals(actualXML, resultXML);
}
public Map<String, String> convertFromPayloadStringToPatchMap(String body, ApiRequestResponseFormat requestFormat) {
try {
if (requestFormat == ApiRequestResponseFormat.JSON) {
return gson.fromJson(body, Map.class);
} else {
// brought in lightweight library to handle this, and this is a hack
Map withHead = gson.fromJson(XML.toJSONObject(body).toString(), Map.class);
ArrayList outer = new ArrayList();
outer.addAll(withHead.keySet());
return (Map<String, String>) withHead.get(outer.get(0));
}
}catch(Exception e){
e.printStackTrace();
return null;
}
}
/**
* Tests that control characters are escaped.
*/
@Test
public void testJsonToXmlEscape(){
final String jsonSrc = "{\"amount\":\"10,00 €\","
+ "\"description\":\"Ação Válida\u0085\","
+ "\"xmlEntities\":\"\\\" ' & < >\""
+ "}";
JSONObject json = new JSONObject(jsonSrc);
String xml = XML.toString(json);
//test control character not existing
assertFalse("Escaping \u0085 failed. Found in XML output.", xml.contains("\u0085"));
assertTrue("Escaping \u0085 failed. Entity not found in XML output.", xml.contains("…"));
// test normal unicode existing
assertTrue("Escaping € failed. Not found in XML output.", xml.contains("€"));
assertTrue("Escaping ç failed. Not found in XML output.", xml.contains("ç"));
assertTrue("Escaping ã failed. Not found in XML output.", xml.contains("ã"));
assertTrue("Escaping á failed. Not found in XML output.", xml.contains("á"));
// test XML Entities converted
assertTrue("Escaping \" failed. Not found in XML output.", xml.contains("""));
assertTrue("Escaping ' failed. Not found in XML output.", xml.contains("'"));
assertTrue("Escaping & failed. Not found in XML output.", xml.contains("&"));
assertTrue("Escaping < failed. Not found in XML output.", xml.contains("<"));
assertTrue("Escaping > failed. Not found in XML output.", xml.contains(">"));
}
/**
* Converting a JSON doc containing a named array to JSONObject, then
* XML.toString() should result in valid XML.
*/
@Test
public void shouldHandleArraytoString() {
String expectedStr =
"{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+
"\"something\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+
"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}";
JSONObject expectedJsonObject = new JSONObject(expectedStr);
String finalStr = XML.toString(expectedJsonObject);
String expectedFinalStr = "<addresses><address><name/><nocontent/>"+
"<something>1</something><something>2</something><something>3</something>"+
"</address><xsi:noNamespaceSchemaLocation>test.xsd</xsi:noName"+
"spaceSchemaLocation><xmlns:xsi>http://www.w3.org/2001/XMLSche"+
"ma-instance</xmlns:xsi></addresses>";
assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+
finalStr+"]", expectedFinalStr.equals(finalStr));
}
public void saveInFile(Path path) throws IOException {
try {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(new InputSource(new StringReader(XML.toString(toJSON()))));
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
t.setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
OutputStreamWriter stream = new OutputStreamWriter(new FileOutputStream(path.resolve(name + ".preset")), "UTF-8");
t.transform(new DOMSource(doc), new StreamResult(stream));
} catch(Exception ex){
Main.log(ex);
Main.log("Error while writing preset file");
}
}
public static CharacterPreset getFromFileUnsafe(File path) {
try {
if (!path.isAbsolute())
path = Main.getPluginProxy().getAssetsDirPath().resolve("presets").resolve(path.getName());
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream(path), "UTF-8")
);
final StringBuilder str = new StringBuilder();
String str2;
while ((str2 = in.readLine()) != null) {
str.append(str2);
str.append("\n");
}
JSONObject obj = XML.toJSONObject(str.toString());
return new CharacterPreset(obj.getJSONObject("preset"));
} catch (Exception e) {
Main.log(e);
return new CharacterPreset();
}
}
@Override
public Object xmlToJson(String xmlContent) {
// Just print it so that anyone can pick the
// formatted xml for their usage from the console.
prettyXml(xmlContent);
String jsonNotPretty = XML.toJSONObject(xmlContent).toString();
try {
return mapper.readTree(jsonNotPretty);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("XmlToJson conversion problem- " + e.getMessage());
}
}
/**
* Converting a JSON doc containing a 'content' array to JSONObject, then
* XML.toString() should result in valid XML.
* TODO: This is probably an error in how the 'content' keyword is used.
*/
@Test
public void shouldHandleContentArraytoString() {
String expectedStr =
"{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+
"content\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+
"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}";
JSONObject expectedJsonObject = new JSONObject(expectedStr);
String finalStr = XML.toString(expectedJsonObject);
String expectedFinalStr = "<addresses><address><name/><nocontent/>"+
"1\n2\n3"+
"</address><xsi:noNamespaceSchemaLocation>test.xsd</xsi:noName"+
"spaceSchemaLocation><xmlns:xsi>http://www.w3.org/2001/XMLSche"+
"ma-instance</xmlns:xsi></addresses>";
assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+
finalStr+"]", expectedFinalStr.equals(finalStr));
}
/**
* Invalid XML string (tag contains a frontslash).
* Expects a JSONException
*/
@Test
public void shouldHandleInvalidSlashInTag() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name/x>\n"+
" <street>abc street</street>\n"+
" </address>\n"+
"</addresses>";
try {
XML.toJSONObject(xmlStr, XMLParserConfiguration.KEEP_STRINGS);
fail("Expecting a JSONException");
} catch (JSONException e) {
assertEquals("Expecting an exception message",
"Misshaped tag at 176 [character 14 line 4]",
e.getMessage());
}
}
/**
* Invalid XML string ('!' char and no closing tag brace)
* Expects a JSONException
*/
@Test
public void shouldHandleInvalidBangNoCloseInTag() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name/>\n"+
" <!\n"+
" </address>\n"+
"</addresses>";
try {
XML.toJSONObject(xmlStr, XMLParserConfiguration.KEEP_STRINGS);
fail("Expecting a JSONException");
} catch (JSONException e) {
assertEquals("Expecting an exception message",
"Misshaped meta tag at 213 [character 12 line 7]",
e.getMessage());
}
}
/**
* Invalid XML string (no end brace for tag)
* Expects JSONException
*/
@Test
public void shouldHandleNoCloseStartTag() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name/>\n"+
" <abc\n"+
" </address>\n"+
"</addresses>";
try {
XML.toJSONObject(xmlStr, XMLParserConfiguration.KEEP_STRINGS);
fail("Expecting a JSONException");
} catch (JSONException e) {
assertEquals("Expecting an exception message",
"Misplaced '<' at 193 [character 4 line 6]",
e.getMessage());
}
}
/**
* Invalid XML string (partial CDATA chars in tag name)
* Expects JSONException
*/
@Test
public void shouldHandleInvalidCDATABangInTag() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name>Joe Tester</name>\n"+
" <![[]>\n"+
" </address>\n"+
"</addresses>";
try {
XMLParserConfiguration config =
new XMLParserConfiguration("altContent");
XML.toJSONObject(xmlStr, config);
fail("Expecting a JSONException");
} catch (JSONException e) {
assertEquals("Expecting an exception message",
"Expected 'CDATA[' at 204 [character 11 line 5]",
e.getMessage());
}
}
/**
* No SML start tag. The ending tag ends up being treated as content.
*/
@Test
public void shouldHandleNoStartTag() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name/>\n"+
" <nocontent/>>\n"+
" </address>\n"+
"</addresses>";
String expectedStr =
"{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+
"content\":\">\"},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+
"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}";
JSONObject jsonObject = XML.toJSONObject(xmlStr,
XMLParserConfiguration.KEEP_STRINGS);
JSONObject expectedJsonObject = new JSONObject(expectedStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
/**
* Valid XML with comments to JSONObject
*/
@Test
public void shouldHandleCommentsInXML() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<!-- this is a comment -->\n"+
"<addresses>\n"+
" <address>\n"+
" <![CDATA[ this is -- <another> comment ]]>\n"+
" <name>Joe Tester</name>\n"+
" <!-- this is a - multi line \n"+
" comment -->\n"+
" <street>Baker street 5</street>\n"+
" </address>\n"+
"</addresses>";
XMLParserConfiguration config =
new XMLParserConfiguration("altContent");
JSONObject jsonObject = XML.toJSONObject(xmlStr, config);
String expectedStr = "{\"addresses\":{\"address\":{\"street\":\"Baker "+
"street 5\",\"name\":\"Joe Tester\",\"altContent\":\" this is -- "+
"<another> comment \"}}}";
JSONObject expectedJsonObject = new JSONObject(expectedStr);
Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
/**
* Converting a JSON doc containing '>' content to JSONObject, then
* XML.toString() should result in valid XML.
*/
@Test
public void shouldHandleContentNoArraytoString() {
String expectedStr =
"{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+
"altContent\":\">\"},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+
"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}";
JSONObject expectedJsonObject = new JSONObject(expectedStr);
XMLParserConfiguration config = new XMLParserConfiguration("altContent");
String finalStr = XML.toString(expectedJsonObject, null, config);
String expectedFinalStr = "<addresses><address><name/><nocontent/>>"+
"</address><xsi:noNamespaceSchemaLocation>test.xsd</xsi:noName"+
"spaceSchemaLocation><xmlns:xsi>http://www.w3.org/2001/XMLSche"+
"ma-instance</xmlns:xsi></addresses>";
assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+
finalStr+"]", expectedFinalStr.equals(finalStr));
}
/**
* Converting a JSON doc containing a 'content' array to JSONObject, then
* XML.toString() should result in valid XML.
* TODO: This is probably an error in how the 'content' keyword is used.
*/
@Test
public void shouldHandleContentArraytoString() {
String expectedStr =
"{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+
"altContent\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+
"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}";
JSONObject expectedJsonObject = new JSONObject(expectedStr);
XMLParserConfiguration config = new XMLParserConfiguration("altContent");
String finalStr = XML.toString(expectedJsonObject, null, config);
String expectedFinalStr = "<addresses><address><name/><nocontent/>"+
"1\n2\n3"+
"</address><xsi:noNamespaceSchemaLocation>test.xsd</xsi:noName"+
"spaceSchemaLocation><xmlns:xsi>http://www.w3.org/2001/XMLSche"+
"ma-instance</xmlns:xsi></addresses>";
assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+
finalStr+"]", expectedFinalStr.equals(finalStr));
}
/**
* Converting a JSON doc containing a named array to JSONObject, then
* XML.toString() should result in valid XML.
*/
@Test
public void shouldHandleArraytoString() {
String expectedStr =
"{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+
"\"something\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+
"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}";
JSONObject expectedJsonObject = new JSONObject(expectedStr);
String finalStr = XML.toString(expectedJsonObject, null,
XMLParserConfiguration.KEEP_STRINGS);
String expectedFinalStr = "<addresses><address><name/><nocontent/>"+
"<something>1</something><something>2</something><something>3</something>"+
"</address><xsi:noNamespaceSchemaLocation>test.xsd</xsi:noName"+
"spaceSchemaLocation><xmlns:xsi>http://www.w3.org/2001/XMLSche"+
"ma-instance</xmlns:xsi></addresses>";
assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+
finalStr+"]", expectedFinalStr.equals(finalStr));
}
/**
* Tests that the XML output for empty arrays is consistent.
*/
@Test
public void shouldHandleEmptyArray(){
final JSONObject jo1 = new JSONObject();
jo1.put("array",new Object[]{});
final JSONObject jo2 = new JSONObject();
jo2.put("array",new JSONArray());
final String expected = "<jo></jo>";
String output1 = XML.toString(jo1, "jo",
XMLParserConfiguration.KEEP_STRINGS);
assertEquals("Expected an empty root tag", expected, output1);
String output2 = XML.toString(jo2, "jo",
XMLParserConfiguration.KEEP_STRINGS);
assertEquals("Expected an empty root tag", expected, output2);
}
/**
* Tests that the XML output for arrays is consistent when an internal array is empty.
*/
@Test
public void shouldHandleEmptyMultiArray(){
final JSONObject jo1 = new JSONObject();
jo1.put("arr",new Object[]{"One", new String[]{}, "Four"});
final JSONObject jo2 = new JSONObject();
jo2.put("arr",new JSONArray(new Object[]{"One", new JSONArray(new String[]{}), "Four"}));
final String expected = "<jo><arr>One</arr><arr></arr><arr>Four</arr></jo>";
String output1 = XML.toString(jo1, "jo",
XMLParserConfiguration.KEEP_STRINGS);
assertEquals("Expected a matching array", expected, output1);
String output2 = XML.toString(jo2, "jo",
XMLParserConfiguration.KEEP_STRINGS);
assertEquals("Expected a matching array", expected, output2);
}
/**
* Tests that the XML output for arrays is consistent when arrays are not empty.
*/
@Test
public void shouldHandleNonEmptyArray(){
final JSONObject jo1 = new JSONObject();
jo1.put("arr",new String[]{"One", "Two", "Three"});
final JSONObject jo2 = new JSONObject();
jo2.put("arr",new JSONArray(new String[]{"One", "Two", "Three"}));
final String expected = "<jo><arr>One</arr><arr>Two</arr><arr>Three</arr></jo>";
String output1 = XML.toString(jo1, "jo",
XMLParserConfiguration.KEEP_STRINGS);
assertEquals("Expected a non empty root tag", expected, output1);
String output2 = XML.toString(jo2, "jo",
XMLParserConfiguration.KEEP_STRINGS);
assertEquals("Expected a non empty root tag", expected, output2);
}
/**
* Tests that the XML output for arrays is consistent when arrays are not empty and contain internal arrays.
*/
@Test
public void shouldHandleMultiArray(){
final JSONObject jo1 = new JSONObject();
jo1.put("arr",new Object[]{"One", new String[]{"Two", "Three"}, "Four"});
final JSONObject jo2 = new JSONObject();
jo2.put("arr",new JSONArray(new Object[]{"One", new JSONArray(new String[]{"Two", "Three"}), "Four"}));
final String expected = "<jo><arr>One</arr><arr><array>Two</array><array>Three</array></arr><arr>Four</arr></jo>";
String output1 = XML.toString(jo1, "jo",
XMLParserConfiguration.KEEP_STRINGS);
assertEquals("Expected a matching array", expected, output1);
String output2 = XML.toString(jo2, "jo",
XMLParserConfiguration.KEEP_STRINGS);
assertEquals("Expected a matching array", expected, output2);
}
/**
* Converting a JSON doc containing a named array of nested arrays to
* JSONObject, then XML.toString() should result in valid XML.
*/
@Test
public void shouldHandleNestedArraytoString() {
String xmlStr =
"{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+
"\"outer\":[[1], [2], [3]]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+
"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}";
JSONObject jsonObject = new JSONObject(xmlStr);
String finalStr = XML.toString(jsonObject, null,
XMLParserConfiguration.ORIGINAL);
JSONObject finalJsonObject = XML.toJSONObject(finalStr);
String expectedStr = "<addresses><address><name/><nocontent/>"+
"<outer><array>1</array></outer><outer><array>2</array>"+
"</outer><outer><array>3</array></outer>"+
"</address><xsi:noNamespaceSchemaLocation>test.xsd</xsi:noName"+
"spaceSchemaLocation><xmlns:xsi>http://www.w3.org/2001/XMLSche"+
"ma-instance</xmlns:xsi></addresses>";
JSONObject expectedJsonObject = XML.toJSONObject(expectedStr,
XMLParserConfiguration.ORIGINAL);
Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject);
}
/**
* Possible bug:
* Illegal node-names must be converted to legal XML-node-names.
* The given example shows 2 nodes which are valid for JSON, but not for XML.
* Therefore illegal arguments should be converted to e.g. an underscore (_).
*/
@Test
public void shouldHandleIllegalJSONNodeNames()
{
JSONObject inputJSON = new JSONObject();
inputJSON.append("123IllegalNode", "someValue1");
inputJSON.append("[email protected]", "someValue2");
String result = XML.toString(inputJSON, null,
XMLParserConfiguration.KEEP_STRINGS);
/*
* This is invalid XML. Names should not begin with digits or contain
* certain values, including '@'. One possible solution is to replace
* illegal chars with '_', in which case the expected output would be:
* <___IllegalNode>someValue1</___IllegalNode><Illegal_node>someValue2</Illegal_node>
*/
String expected = "<123IllegalNode>someValue1</123IllegalNode><[email protected]>someValue2</[email protected]>";
assertEquals(expected, result);
}
/**
* JSONObject with NULL value, to XML.toString()
*/
@Test
public void shouldHandleNullNodeValue()
{
JSONObject inputJSON = new JSONObject();
inputJSON.put("nullValue", JSONObject.NULL);
// This is a possible preferred result
// String expectedXML = "<nullValue/>";
/**
* This is the current behavior. JSONObject.NULL is emitted as
* the string, "null".
*/
String actualXML = "<nullValue>null</nullValue>";
String resultXML = XML.toString(inputJSON, null,
XMLParserConfiguration.KEEP_STRINGS);
assertEquals(actualXML, resultXML);
}
/**
* test passes when using the new method toJsonArray.
*/
@Test
public void testToJsonXML() {
final String originalXml = "<root><id>01</id><id>1</id><id>00</id><id>0</id><item id=\"01\"/><title>True</title></root>";
final String expectedJsonString = "{\"root\":{\"item\":{\"id\":\"01\"},\"id\":[\"01\",\"1\",\"00\",\"0\"],\"title\":\"True\"}}";
final JSONObject json = XML.toJSONObject(originalXml,
new XMLParserConfiguration(true));
assertEquals(expectedJsonString, json.toString());
final String reverseXml = XML.toString(json);
// this reversal isn't exactly the same. use JSONML for an exact reversal
final String expectedReverseXml = "<root><item><id>01</id></item><id>01</id><id>1</id><id>00</id><id>0</id><title>True</title></root>";
assertEquals(expectedReverseXml, reverseXml);
}
/**
* Invalid XML string (tag contains a frontslash).
* Expects a JSONException
*/
@Test
public void shouldHandleInvalidSlashInTag() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name/x>\n"+
" <street>abc street</street>\n"+
" </address>\n"+
"</addresses>";
try {
XML.toJSONObject(xmlStr);
fail("Expecting a JSONException");
} catch (JSONException e) {
assertEquals("Expecting an exception message",
"Misshaped tag at 176 [character 14 line 4]",
e.getMessage());
}
}
/**
* Invalid XML string ('!' char and no closing tag brace)
* Expects a JSONException
*/
@Test
public void shouldHandleInvalidBangNoCloseInTag() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name/>\n"+
" <!\n"+
" </address>\n"+
"</addresses>";
try {
XML.toJSONObject(xmlStr);
fail("Expecting a JSONException");
} catch (JSONException e) {
assertEquals("Expecting an exception message",
"Misshaped meta tag at 213 [character 12 line 7]",
e.getMessage());
}
}
/**
* Invalid XML string (no end brace for tag)
* Expects JSONException
*/
@Test
public void shouldHandleNoCloseStartTag() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name/>\n"+
" <abc\n"+
" </address>\n"+
"</addresses>";
try {
XML.toJSONObject(xmlStr);
fail("Expecting a JSONException");
} catch (JSONException e) {
assertEquals("Expecting an exception message",
"Misplaced '<' at 193 [character 4 line 6]",
e.getMessage());
}
}
/**
* Invalid XML string (partial CDATA chars in tag name)
* Expects JSONException
*/
@Test
public void shouldHandleInvalidCDATABangInTag() {
String xmlStr =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
"<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
" xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
" <address>\n"+
" <name>Joe Tester</name>\n"+
" <![[]>\n"+
" </address>\n"+
"</addresses>";
try {
XML.toJSONObject(xmlStr);
fail("Expecting a JSONException");
} catch (JSONException e) {
assertEquals("Expecting an exception message",
"Expected 'CDATA[' at 204 [character 11 line 5]",
e.getMessage());
}
}