Java : Convert formatted xml file to one line string

前端 未结 10 1182
时光取名叫无心
时光取名叫无心 2020-12-01 04:02

I have a formatted XML file, and I want to convert it to one line string, how can I do that.

Sample xml:



        
相关标签:
10条回答
  • 2020-12-01 04:14
    // 1. Read xml from file to StringBuilder (StringBuffer)
    // 2. call s = stringBuffer.toString()
    // 3. remove all "\n" and "\t": 
    s.replaceAll("\n",""); 
    s.replaceAll("\t","");
    

    edited:

    I made a small mistake, it is better to use StringBuilder in your case (I suppose you don't need thread-safe StringBuffer)

    0 讨论(0)
  • 2020-12-01 04:14

    In java 1.8 and above

    BufferedReader br = new BufferedReader(new FileReader(filePath));
    String content = br.lines().collect(Collectors.joining("\n"));
    
    0 讨论(0)
  • 2020-12-01 04:20

    I guess you want to read in, ignore the white space, and write it out again. Most XML packages have an option to ignore white space. For example, the DocumentBuilderFactory has setIgnoringElementContentWhitespace for this purpose.

    Similarly if you are generating the XML by marshaling an object then JAXB has JAXB_FORMATTED_OUTPUT

    0 讨论(0)
  • 2020-12-01 04:21

    Underscore-java library has static method U.formatXml(xmlstring). I am the maintainer of the project. Live example

    import com.github.underscore.lodash.U;
    import com.github.underscore.lodash.Xml;
    
    public class MyClass {
        public static void main(String[] args) {
            System.out.println(U.formatXml("<a>\n  <b></b>\n  <b></b>\n</a>",
            Xml.XmlStringBuilder.Step.COMPACT));
        }
    }
    
    // output: <a><b></b><b></b></a>
    
    0 讨论(0)
  • 2020-12-01 04:25
    FileUtils.readFileToString(fileName);
    

    link

    0 讨论(0)
  • 2020-12-01 04:27

    Open and read the file.

    Reader r = new BufferedReader(filename);
    String ret = "";
    while((String s = r.nextLine()!=null)) 
    {
      ret+=s;
    }
    return ret;
    
    0 讨论(0)
提交回复
热议问题