Search code examples
javaxmljsoup

Jsoup display all text() at the line


My original xml file is:

   </Toto>
      <Ride>5</Ride>
   </Toto>
   <Document>
      <a>
         <b>1234</b>
         <c>foo</c>
         <d>bar</d>
      </a>
   <Document>

I want change 1234 by 5678.

File f = new File(filePath);
Document doc = Jsoup.parse(new FileInputStream(f), "UTF-8", f.getAbsolutePath(), Parser.xmlParser());
Element elem = doc.select("Document > a > b").first();
TextNode tn = elem.textNodes().get(0);
tn.replaceWith(new TextNode("5478"));
value = doc.toString();

My output is xlm file is:

   </Toto>
      <Ride>
       5
      </Ride>
   </Toto>
   <Document>
      <a>
         <b>
          5478
         </b>
         <c>
          foo
         </c>
         <d>
          bar
         </d>
      </a>
   <Document>

Solution

  • Could you please try following statement before toString()

    doc.outputSettings().prettyPrint(false);

    I've also found pretty much same problem How to convert Jsoup Document in a String without put spaces