简体   繁体   English

从字符串中删除空格,然后转换为XML

[英]Removing whitespaces from String and then convert to XML

I want to remove white space from a string and then convert it to XML. 我想从字符串中删除空格,然后将其转换为XML。 This is my string: 这是我的字符串:

<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>
                        ...

I can remove the white space using str.replaceall("\\\\s+","") . 我可以使用str.replaceall("\\\\s+","")删除空格。 But while converting from string to XML, it is showing an error, because it removes the space between element and attribute. 但是,当从字符串转换为XML时,它显示了错误,因为它删除了元素和属性之间的空格。 It gives a result of <cursornumRows="0" sameConnection="false"/> when the actual element is <cursor numRows="0" sameConnection="false"/> . 它给出的结果<cursornumRows="0" sameConnection="false"/>当实际元件是<cursor numRows="0" sameConnection="false"/> The space between element cursor and attribute numRows is removed. 元素cursor和属性numRows之间的空间已删除。

Can anyone help me? 谁能帮我?

You don't need to remove whitespace before converting it to XML. 在将空格转换为XML之前,无需删除空格。 Simply 只是

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
DocumentBuilder builder = factory.newDocumentBuilder();  
Document document = builder.parse(new InputSource(new StringReader(xmlString)));

will work. 将工作。 When you convert the XML document back to a string, the whitespace will disappear (by default - there are some options for pretty-printing as well): 当您将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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM