0

I'm reading a customers object through XStream and then replacing any tags I don't need with blanks. Since the customers contain multiple customer it contains the xml form of them. The last .replaceAll("\\<\\?xml(.+?)\\?\\>", "") gets rid of excess <?xml version="1.0" encoding="UTF-8"?> inside the customers string.

I've tried finding <?xml version="1.0"?> then replacing it with <?xml version="1.0" encoding="UTF-8"?> but it caused no change. The final input starts with this:

<?xml version="1.0"?>

But I want to include the encoding="UTF-8"

How would include that part after I clean up the tags?

Here is the relevant code for the XML and writing it to a file.

    //Final XML string of customers
    String xml = xstream.toXML(customers);

    //Remove regex and excess tags
    xml = String.format(xml.replaceAll("<string>", "")
        .replaceAll("</string>", "")
        .replaceAll("<customers>", "")
        .replaceAll("</customers>", "")
        .replaceAll("&lt;", "<")
        .replaceAll("&#13;", "")
        .replaceAll("&gt;", ">")
        .replaceAll("\\<\\?xml(.+?)\\?\\>", ""), 4);

    System.out.println(xml);

    //Create file of grouped XML in a sub-folder
    String timeStamp = new SimpleDateFormat("MM dd yyyy hh.mm.ss a").format(new Date());
    FileWriter fw = new FileWriter("XML Claims\\All Customers" + " " + timeStamp + ".xml");
    fw.write(xml);
    fw.close();

Customers object:

public class Customers {
    //this is a string version of customer object converted through xstream
    public ArrayList<String> customers = new ArrayList<String>();
    public String XMLCreationDate = null;
    public int totalNumberOfRecords = 0;
}

Customer object:

public class Customer {
    public LetterContent letterContent = null;
    public LetterIdentifierInformation letterIdentifierInformation = null;
    public Addressee addressee = null;
}

Current XML:

<?xml version="1.0"?>
<Customers>
     <Customer>
          <letterContent></letterContent>
          <addressee></address>
     </Customer>
</Customers>

Desired XML:

<?xml version="1.0" encoding="UTF-8"?>
<Customers>
     <Customer>
          <letterContent></letterContent>
          <addressee></address>
     </Customer>
</Customers>
2

1 Answer 1

2

you can do like following

XStream xstream = new xStream();  
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();  
Writer writer = new OutputStreamWriter(outputStream, "UTF-8");  
xStream.toXML(object, writer);  
String xml = outputStream.toString("UTF-8");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.