我正在阅读 customers
通过 XStream 对象,然后用空白替换我不需要的任何标签。自 customers
包含多个customer
它包含它们的 xml 形式。最后.replaceAll("\\<\\?xml(.+?)\\?\\>", "")
摆脱多余的<?xml version="1.0" encoding="UTF-8"?>
里面customers
字符串。
我尝试查找<?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("<", "<")
.replaceAll(" ", "")
.replaceAll(">", ">")
.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>
最佳答案
你可以像下面这样做
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");
关于java - 如何在Java中的xml字符串中包含 "encoding="UTF-8""?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31862049/