【问题标题】:How to include "encoding="UTF-8"" in xml string in Java?如何在 Java 的 xml 字符串中包含“encoding="UTF-8"”?
【发布时间】:2015-08-06 17:23:49
【问题描述】:

我正在通过 XStream 读取 customers 对象,然后将我不需要的任何标签替换为空白。由于customers 包含多个customer,它包含它们的xml 形式。最后一个.replaceAll("\\<\\?xml(.+?)\\?\\>", "") 去掉了customers 字符串中多余的<?xml version="1.0" encoding="UTF-8"?>

我尝试找到<?xml version="1.0"?>,然后将其替换为<?xml version="1.0" encoding="UTF-8"?>,但没有造成任何变化。最后的输入是这样开始的:

<?xml version="1.0"?>

但我想包含encoding="UTF-8"

我清理标签后如何包含该部分?

这是 XML 的相关代码并将其写入文件。

    //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();

客户对象:

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;
}

客户对象:

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

当前 XML:

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

所需的 XML:

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

【问题讨论】:

标签: java xml string utf-8 xstream


【解决方案1】:

你可以这样做

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");

【讨论】:

    猜你喜欢
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 2012-07-01
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    相关资源
    最近更新 更多