[英]Removing whitespaces from String and then convert to XML
我想從字符串中刪除空格,然后將其轉換為XML。 這是我的字符串:
<XMLDoc>
<Envelope>
<Header>
<header>
<msg-id>000C2990-2FBD-11E5-E6CF-FB0900F491A5</msg-id>
</header>
</Header>
<Body>
<GetWorkItemsResponse>
<cursor
numRows="0"
sameConnection="false"
/>
<tuple
>
<old>
<TaskInfo>
...
我可以使用str.replaceall("\\\\s+","")
刪除空格。 但是,當從字符串轉換為XML時,它顯示了錯誤,因為它刪除了元素和屬性之間的空格。 它給出的結果<cursornumRows="0" sameConnection="false"/>
當實際元件是<cursor numRows="0" sameConnection="false"/>
元素cursor
和屬性numRows
之間的空間已刪除。
誰能幫我?
在將空格轉換為XML之前,無需刪除空格。 只是
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xmlString)));
將工作。 當您將XML文檔轉換回字符串時,空格將消失(默認情況下-漂亮打印還有一些選項):
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String outputString = writer.getBuffer().toString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.