當前位置: 首頁>>代碼示例>>Java>>正文


Java XML類代碼示例

本文整理匯總了Java中org.json.XML的典型用法代碼示例。如果您正苦於以下問題:Java XML類的具體用法?Java XML怎麽用?Java XML使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


XML類屬於org.json包,在下文中一共展示了XML類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: process

import org.json.XML; //導入依賴的package包/類
private void process(Response<String> response, ApiManagerInterface callback, Class clazz) {
    if (response.isSuccessful()) {
        String xml = response.body();
        try {
            JSONObject jsonObj;
            if (xml != null) {
                jsonObj = XML.toJSONObject(xml);
            } else {
                callback.onError(new IOException("response body is null"));
                return;
            }
            if (isVerboseLog) {
                System.out.println(jsonObj);
            }
            callback.onResult(new Gson().fromJson(jsonObj.toString(), clazz));
        } catch (JSONException e) {
            callback.onError(e);
            e.printStackTrace();
        }
    } else {
        handleUnsucceesfulResponse(response, callback);
    }
}
 
開發者ID:tamasberes,項目名稱:yajwfs,代碼行數:24,代碼來源:ShoutCastApi.java

示例2: convert

import org.json.XML; //導入依賴的package包/類
/**
 * Converts the given XML string to JSON string. class.
 *
 * @param data XML string
 * @return JSON string or an empty string if the conversion fails
 */
@Override
public String convert(String data) {
    LOGGER.debug("CONVERTING " + data);
    try {
        JSONObject asJson = XML.toJSONObject(data);
        if (asJson.has(ARRAY)) {
            // If the JSON object has an "array" key, it's an array
            JSONArray jsonArray = asJson.getJSONArray(ARRAY);
            LOGGER.debug("RETURN ARRAY " + jsonArray.toString());
            return jsonArray.toString();
        } else {
            // Did not have top-level array key.
            this.normalizeObject(asJson);
            String jsonStr = asJson.toString();
            // JSON-LD uses '@' characters in keys and they're not allowed
            // in XML element names. Replace '__at__' with '@' in keys.
            jsonStr = jsonStr.replaceAll("\"__at__(.+?\"\\s*:)", "\"@$1");
            LOGGER.debug("NORMALIZED TO " + jsonStr);
            return jsonStr;
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        LOGGER.warn("Converting XML to JSON failed! An empty String is returned.");
        return "";
    }
}
 
開發者ID:vrk-kpa,項目名稱:xrd4j,代碼行數:33,代碼來源:XMLToJSONConverter.java

示例3: shouldHandleCommentsInXML

import org.json.XML; //導入依賴的package包/類
/**
 * 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>";
    JSONObject jsonObject = XML.toJSONObject(xmlStr);
    String expectedStr = "{\"addresses\":{\"address\":{\"street\":\"Baker "+
            "street 5\",\"name\":\"Joe Tester\",\"content\":\" this is -- "+
            "<another> comment \"}}}";
    JSONObject expectedJsonObject = new JSONObject(expectedStr);
    Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
 
開發者ID:stleary,項目名稱:JSON-Java-unit-test,代碼行數:26,代碼來源:XMLTest.java

示例4: shouldHandleIllegalJSONNodeNames

import org.json.XML; //導入依賴的package包/類
/**
 * 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);

    /*
     * 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);
}
 
開發者ID:stleary,項目名稱:JSON-Java-unit-test,代碼行數:26,代碼來源:XMLTest.java

示例5: jsonToXml

import org.json.XML; //導入依賴的package包/類
/**
 * JSON To xml.
 * 
 * @param xmlString the xml string
 * @param rootElement the root element that the xml should have.  
 * By default = gptJsonXml
 * @return the xml. 
 * @throws Exception thrown if error while converting xmlString
 */
public static String jsonToXml(String xmlString, String rootElement) 
  throws Exception {
  try {
    JSONObject jso = new JSONObject(xmlString);
    rootElement = Val.chkStr(rootElement);
    if("".equals(rootElement)) {
      rootElement = "gptJsonXml";
    }
    String xml = XML.toString(jso, "gptJsonXml");
    StreamSource source = new StreamSource(new StringReader(xml));
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(source, result);
    return Val.chkStr(writer.toString());
  } catch (Exception e) {
    throw e;
  }
}
 
開發者ID:usgin,項目名稱:usgin-geoportal,代碼行數:31,代碼來源:XmlIoUtil.java

示例6: getAllZonesForDay

import org.json.XML; //導入依賴的package包/類
/**
 * Save incidents for a given day, returns if any data was added by this call.
 */
static final boolean getAllZonesForDay(final LocalDate localDate) throws Exception {
  JSONObject[] stats = new JSONObject[7];
  
  for (int zoneID = 1; zoneID <= 6; zoneID++) {
    stats[zoneID] = getStats(zoneID + "", localDate);
  }
  
  for (int zoneID = 1; zoneID <= 6; zoneID++) {
    JSONArray incidents = stats[zoneID].getJSONArray("incidents");
    if (incidents.length() == 0) {
      Utilities.println("halting getAllZonesForDay on " + localDate + " because zone " + zoneID + " is empty");
      return false;
    }
  }
  
  for (int zoneID = 1; zoneID <= 6; zoneID++) {
    String xmlString = "<stats>" + XML.toString(stats[zoneID]) + "</stats>";
    MongoData.addIncidentsToCollection(getIncidentsFromXMLString(xmlString));
  }
  
  return true;
}
 
開發者ID:rck109d,項目名稱:atl-pd-data,代碼行數:26,代碼來源:Aggregation.java

示例7: processXML2JSON

import org.json.XML; //導入依賴的package包/類
private String processXML2JSON(Path xmlDocPath) throws JSONException {
    
    
    String XML_STRING = null;
    try {
        XML_STRING = Files.lines(xmlDocPath).collect(Collectors.joining("\n"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    JSONObject xmlJSONObj = XML.toJSONObject(XML_STRING);
    String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
    System.out.println("PRINTING STRING :::::::::::::::::::::" + jsonPrettyPrintString);
    
    return jsonPrettyPrintString;
}
 
開發者ID:michaelcgood,項目名稱:XML-JSON-MongoDB-Spring-Batch-Example,代碼行數:17,代碼來源:JobConfiguration.java

示例8: fetch

import org.json.XML; //導入依賴的package包/類
@SuppressWarnings("UnusedReturnValue")
private static String fetch() {
    try {
        info = Unirest.get("https://gensokyoradio.net/xml").asString().getBody();

        JSONObject data = XML.toJSONObject(GensokyoInfoAgent.getInfo()).getJSONObject("GENSOKYORADIODATA");

        String newSong = data.getJSONObject("SONGINFO").getString("TITLE");

        if (!newSong.equals(lastSong)) {
            List<FredBoat> shards = FredBoat.getShards();
            for(FredBoat shard : shards) {
                shard.getJda().getPresence().setGame(Game.of(newSong));
            }

            log.info("Now playing " + newSong);
        }

        lastSong = data.getJSONObject("SONGINFO").getString("TITLE");

        return info;
    } catch (UnirestException e) {
        throw new RuntimeException(e);
    }
}
 
開發者ID:Frederikam,項目名稱:GensokyoBot,代碼行數:26,代碼來源:GensokyoInfoAgent.java

示例9: xmlFromDOICrossRef

import org.json.XML; //導入依賴的package包/類
private Document xmlFromDOICrossRef(String doi) throws Exception {

        //send request to API
        MCRContent crossRefExport = crossRefConnection.getPublicationByDOI(doi);

        //transform JSON-response to XML
        MCRStringContent xml = new MCRStringContent(XML.toString(new JSONObject(crossRefExport.asString()), "content"));

        //transform xml to mods
        MCRXSL2XMLTransformer transformer = new MCRXSL2XMLTransformer("CrossRef2mods.xsl");
        MCRContent mods = transformer.transform(xml);

        return mods.asXML();
    }
 
開發者ID:ETspielberg,項目名稱:bibliometrics,代碼行數:15,代碼來源:AskAllServlet.java

示例10: resolve

import org.json.XML; //導入依賴的package包/類
/**
 * Reads document description from the CrossRef API.
 *
 * 
 *   @author Eike Spielberg      
 *
 */

public Source resolve(String href, String base) throws TransformerException {
    String id = href.substring(href.indexOf(":") + 1);
    MCRContent content = null;
    IEEEConnector connection = new IEEEConnector();
    try {
        MCRContent ieeeExport = connection.getPublicationByAuthor(id);
        content = new MCRStringContent(XML.toString(new JSONObject(ieeeExport.asString()), "content"));
        LOGGER.debug("Reading MCRContent with DOI " + id);
        MCRXSL2XMLTransformer transformer = new MCRXSL2XMLTransformer("xsl/IEEE2mods.xsl");
        MCRContent mods = transformer.transform(content);
        connection.close();
        return mods.getSource();
    } catch (Exception e) {
        throw new TransformerException(e);
    }
}
 
開發者ID:ETspielberg,項目名稱:bibliometrics,代碼行數:25,代碼來源:MCRIEEEResolver.java

示例11: resolve

import org.json.XML; //導入依賴的package包/類
/**
 * Reads document description from the CrossRef API.
 *
 * 
 *   @author Eike Spielberg      
 *
 */

public Source resolve(String href, String base) throws TransformerException {
    String id = href.substring(href.indexOf(":") + 1);
    MCRContent content = null;
    CrossRefConnector connection = new CrossRefConnector();
    try {
        MCRContent crossRefExport = connection.getPublicationByDOI(id);
        content = new MCRStringContent(XML.toString(new JSONObject(crossRefExport.asString()), "content"));
        LOGGER.debug("Reading MCRContent with DOI " + id);
        MCRXSL2XMLTransformer transformer = new MCRXSL2XMLTransformer("xsl/CrossRef2mods.xsl");
        MCRContent mods = transformer.transform(content);
        connection.close();
        return mods.getSource();
    } catch (Exception e) {
        throw new TransformerException(e);
    }
}
 
開發者ID:ETspielberg,項目名稱:bibliometrics,代碼行數:25,代碼來源:MCRCrossRefResolver.java

示例12: convert

import org.json.XML; //導入依賴的package包/類
/**
 * Converts the given JSON string to XML string.
 * class.
 * @param data JSON string
 * @return XML string or an empty string if the conversion fails
 */
@Override
public String convert(String data) {
    String asXML;
    try {
        LOGGER.debug("CONVERTING " + data);
        if (data.startsWith("{")) {
            JSONObject asJson = new JSONObject(data);

            // "array" behaves in a special way, best to disallow it
            if (asJson.has("array")) {
                LOGGER.error("Data violation: Invalid key \"array\"");
                return "<error>Invalid key \"array\"</error>";
            }
            asXML = XML.toString(asJson);
        } else {
            asXML = XML.toString(new JSONArray(data));
        }
        // JSON-LD uses '@' characters in keys and they're not allowed
        // in XML element names. Replace '@' characters with '__at__' in
        // element names.
        asXML = asXML.replaceAll("<(/{0,1})@", "<$1__at__");
        LOGGER.debug("RETURN XML " + asXML);
        return asXML;
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    LOGGER.warn("Converting JSON to XML failed! An empty string is returned.");
    return "";
}
 
開發者ID:vrk-kpa,項目名稱:xrd4j,代碼行數:36,代碼來源:JSONToXMLConverter.java

示例13: BlockDbH2Impl

import org.json.XML; //導入依賴的package包/類
/**
 * the constructor.
 *
 * @param config
 *            the configuration to use.
 */
public BlockDbH2Impl(final JSONObject config) {
	try (InputStream resourceAsStream = BlockDbH2Impl.class.getResourceAsStream(SQL_CACHE_XML);) {
		final String jsonStr = IOUtils.toString(resourceAsStream, "UTF-8");
		sqlCache = XML.toJSONObject(jsonStr, true).getJSONObject("BlockDbImpl");
	} catch (final IOException | NullPointerException e) {
		throw new RuntimeException("error reading resource\"" + SQL_CACHE_XML + "\" ", e);
	}

	fileSizeDir = new File(config.getString(ConfigurationUtil.FILE_SIZE_DIR));

	ds = new JdbcDataSource();
	ds.setUrl(config.getString(ConfigurationUtil.URL));

	final JdbcTemplate t = new JdbcTemplate(ds);

	executeSqlGroup(t, "create");
}
 
開發者ID:coranos,項目名稱:neo-java,代碼行數:24,代碼來源:BlockDbH2Impl.java

示例14: XMLTextDecode

import org.json.XML; //導入依賴的package包/類
/**
 * Decodes the given XML string to produce a list structure. <tag>string</tag> decodes to
 * a list that contains a pair of tag and string.  More generally, if obj1, obj2, ...
 * are tag-delimited XML strings, then <tag>obj1 obj2 ...</tag> decodes to a list
 * that contains a pair whose first element is tag and whose second element is the
 * list of the decoded obj's, ordered alphabetically by tags.  Examples:
 * <foo>123</foo> decodes to a one-item list containing the pair (foo, 123)
 * <foo>1 2 3</foo> decodes to a one-item list containing the pair (foo,"1 2 3")
 * <a><foo>1 2 3</foo><bar>456</bar></a> decodes to a list containing the pair
 * (a,X) where X is a 2-item list that contains the pair (bar,123) and the pair (foo,"1 2 3").
 * If the sequence of obj's mixes tag-delimited and non-tag-delimited
 * items, then the non-tag-delimited items are pulled out of the sequence and wrapped
 * with a "content" tag.  For example, decoding <a><bar>456</bar>many<foo>1 2 3</foo>apples</a>
 * is similar to above, except that the list X is a 3-item list that contains the additional pair
 * whose first item is the string "content", and whose second item is the list (many, apples).
 * This method signals an error and returns the empty list if the result is not well-formed XML.
 *
 * @param jsonText the JSON text to decode
 * @return the decoded text
 */
 // This method works by by first converting the XML to JSON and then decoding the JSON.
@SimpleFunction(description = "Decodes the given XML string to produce a list structure.  " +
    "See the App Inventor documentation on \"Other topics, notes, and details\" for information.")
// The above description string is punted because I can't figure out how to write the
// documentation string in a way that will look work both as a tooltip and in the autogenerated
// HTML for the component documentation on the Web.  It's too long for a tooltip, anyway.
public Object XMLTextDecode(String XmlText) {
  try {
    JSONObject json = XML.toJSONObject(XmlText);
    return JsonTextDecode(json.toString());
  } catch (JSONException e) {
    // We could be more precise and signal different errors for the conversion to JSON
    // versus the decoding of that JSON, but showing the actual error message should
    // be good enough.
    Log.e("Exception in XMLTextDecode", e.getMessage());
    form.dispatchErrorOccurredEvent(this, "XMLTextDecode",
        ErrorMessages.ERROR_WEB_JSON_TEXT_DECODE_FAILED, e.getMessage());
    // This XMLTextDecode should always return a list, even in the case of an error
    return YailList.makeEmptyList();
  }
}
 
開發者ID:mit-cml,項目名稱:appinventor-extensions,代碼行數:42,代碼來源:Web.java

示例15: getResponse

import org.json.XML; //導入依賴的package包/類
public static List<CareerBuilderJobSearchResult> getResponse (String candidateLocation, String jobQuery) {
	
	// Keywords matching CareerBuilder matched to Indeed : keywords = query, location = location, orderBy = sort, empType = jobType, pageNumber = start
	// perPage = limit, payLow = salary
	String keywords = "keywords=" + jobQuery, location = "location=" + candidateLocation, orderBy = "orderby=", empType = "emptype=", pageNumber = "pagenumber=",
			perPage = "perpage=" + preDefinedLimit, payLow = "paylow=", requestURL = "http://api.careerbuilder.com/v2/jobsearch?";

	// Master URL used to query CB database
	requestURL += developerKey + "&" + keywords + "&" + location + "&" + orderBy + "&" + empType + "&" + pageNumber + "&" + perPage + "&" + payLow;

       try {
           // Reading XML, converting to JSON
           String xml = CustomUtilities.RequestToString(requestURL);
           if (xml != null) {
               String json = XML.toJSONObject(xml).toString();
               Gson gson = new Gson();
               CareerBuilderMaster s = gson.fromJson(json, CareerBuilderMaster.class);
               return s.getResponse().getResult().getJobResults();
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
       return null;
}
 
開發者ID:faizan-ali,項目名稱:full-javaee-app,代碼行數:25,代碼來源:CareerBuilder.java


注:本文中的org.json.XML類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。