Java 如何在从xml解析json时转义新行

Java 如何在从xml解析json时转义新行,java,xml,json,Java,Xml,Json,我正在学习从xml解析json,我解析了它,但当我从xml解析json时,我的json中有了新的行字符。请任何人建议如何删除它,这是我的java代码。 公共类Test2{ private URL url = null; private InputStream inputStream = null; private int test = 4; public void getXMLfromJson() { try { url = th

我正在学习从xml解析json,我解析了它,但当我从xml解析json时,我的json中有了新的行字符。请任何人建议如何删除它,这是我的java代码。 公共类Test2{

private URL url = null;
    private InputStream inputStream = null;
    private int test = 4;

    public void getXMLfromJson() {
        try {
            url = this.getClass().getClassLoader().getResource("sample.xml");
            inputStream = url.openStream();
            String xml = IOUtils.toString(inputStream);
            org.json.JSONObject JSON = XML.toJSONObject(xml);
            String json = JSON.toString(test);
            System.out.println(json);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                url = null;
            } catch (IOException ex) {
            }
        }
    }

    public static void main(String[] args) {
        new Test2().getXMLfromJson();
    }
}
我正在阅读的Xml文件如下:

<!--?xml version="1.0" encoding="UTF-8"?-->
    <catalog>
       <book id="bk01">
          <author>Gambardella, Matthew</author>
          <title>XML Developer's Guide</title>
          <genre>Computer</genre>
          <price>44.95</price>
          <publish_date>2000-10-01</publish_date>
          <description>An in-depth look at creating applications
          with XML.</description>
       </book>
       <book id="bk02">
          <author>Ralls, Kim</author>
          <title>Midnight Rain</title>
          <genre>Fantasy</genre>
          <price>5.95</price>
          <publish_date>2000-12-16</publish_date>
          <description>A former architect battles corporate zombies,
          an evil sorceress, and her own childhood to become queen
          of the world.</description>
       </book>
    </catalog>

如何转义这个\n新行字符和空格。

我认为您应该找到一种方法,使您的XML没有这些字符和空格。您上面所做的只是转换,而不是转换。

只是共享我的解决方案。只需在将XML转换为JSON之前替换XML中的换行符即可

//to replace line break in XML
public string escapeLineBreak(string myXml) {
   if (myXml != null && myXml != "") {
        return myXml.Replace("\r\n", "\\n");
   } else {
        return myXml;
   }
}

你说的“逃跑”是什么意思?给定原始源代码,JSON输出非常完美——它包含XML中的文本。包括换行符和空格!我不想包含换行符和空格请告诉我
XML
IOUtils
类的第三方库。让我们看看这些API中是否有一些方法可以满足您的需要。
//to replace line break in XML
public string escapeLineBreak(string myXml) {
   if (myXml != null && myXml != "") {
        return myXml.Replace("\r\n", "\\n");
   } else {
        return myXml;
   }
}