Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从现在作为字符串的xml中删除空间?_Java_Xml - Fatal编程技术网

Java 如何从现在作为字符串的xml中删除空间?

Java 如何从现在作为字符串的xml中删除空间?,java,xml,Java,Xml,Sample.xml: <?xml version="1.0" encoding="UTF-8" ?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note&

Sample.xml:

<?xml version="1.0" encoding="UTF-8" ?>    
<note> 
  <to>Tove</to>  
  <from>Jani</from> 
  <heading>Reminder</heading> 
  <body>Don't forget me this weekend!</body> 
</note>
此方法和xml是正确的。然而,当打印x的值时,我得到了空格。我想删除这些空格。我试过x.repalcell\\\s;但这并没有起作用——空间仍然存在。我也试过x.replace;但这也没有消除空间。有人能帮我吗?当下一行包含标记时,将包含空格。

您应该使用x.appendline.trim;而不是x.appendline

FileInputStream fi = new FileInputStream(file);
            byte[] downloadStream = new byte[(int) file.length()];
            fi.read(downloadStream);
            InputStream is = new ByteArrayInputStream(downloadStream); // read it with BufferedReader
            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            String line;

            while ((line = br.readLine()) != null) {
                x.append(line.trim());
            }

你刚做了x.replace。。。或x=x。替换。。。?字符串是不可变的。您必须将替换结果分配给一个变量,;x、 toString.replace,;太不起作用。根据您的问题,由于将文件读入字符串缓冲区是有效的,问题在于替换空格,因此您可能应该发布该代码,以及如何打印替换的字符串。请共享用于打印此字符串的代码,即替换空格的代码。并且分享最终的结果,这些都有空间。我之前就试过了。我使用的这段代码是我正在编写的Junit测试用例的一部分。我已经将xml文件包含在src/test/resources中,该方法包含在src/test/java中的一个包中。因此,当我传递代码中提到的文件时,这将不起作用。谢谢。但是有没有其他方法可以从字符串中删除不同长度的空格?它怎么会抛出SAXParseException?您向我们展示的所有代码都没有使用SAX解析器?我发布了该方法和xml文件,以便您了解我从何处获得字符串。我的问题是:有没有其他方法可以从字符串中删除不同长度的空格?你能帮我吗?这样,我一点也不知道。
FileInputStream fi = new FileInputStream(file);
            byte[] downloadStream = new byte[(int) file.length()];
            fi.read(downloadStream);
            InputStream is = new ByteArrayInputStream(downloadStream); // read it with BufferedReader
            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            String line;

            while ((line = br.readLine()) != null) {
                x.append(line.trim());
            }