簡體   English   中英

解析XML字符串不會在標記內保留空格

[英]Parsing an XML String does not preserve white spaces inside tag

我有一個帶有這樣的標簽的XML字符串:

<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />

請注意“ />”前的空白。 根據我的規范,我必須保留此空白,但是每次我解析字符串時,解析器都會擦除該空白。

這是我的代碼(“行”是XML字符串):

byte[] base64DecodedResponse = Base64.decode(line);
InputStream stream = new ByteArrayInputStream(base64DecodedResponse);

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
documentBuilderFactory.setIgnoringElementContentWhitespace(true);
documentBuilderFactory.setValidating(true);

DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();

Document document = docBuilder.parse(stream);

我試圖更改解析器(Sax而不是javax.xml.parser),但問題仍然存在。 有什么辦法嗎? 謝謝。

我看到兩種可能性:

  1. 遍歷XML樹(在document ),然后將結果寫入字符串行。

  2. 使用您擁有的打印方法,然后執行replaceAll,將每次出現的“ />”替換為“ />”,例如

     String result = result.replaceAll("\\\\/\\\\>", " />"); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM