How to remove the white spaces between tags in XML

后端 未结 7 905
太阳男子
太阳男子 2020-12-06 18:00

I created an XML document using Java in my android application. I have to call a web service in my application and pass this XML as an argument there. But my problem is ther

相关标签:
7条回答
  • 2020-12-06 18:17

    You can create a copy of all nodes in a document, and trims the nodeValue of each node if it exists.

    const copyChildrenNodesWithoutWhiteSpace = (document) => {
      const clone = document.cloneNode();
    
      for (const child of document.childNodes) {
        const childCopy = copyChildrenNodesWithoutWhiteSpace(child);
        clone.appendChild(childCopy);
    
        if (childCopy.nodeValue) {
          childCopy.nodeValue = childCopy.nodeValue.trim();
        }
      }
    
      return clone;
    };
    
    const result = copyChildrenNodesWithoutWhiteSpace(anyDocument);
    
    0 讨论(0)
  • 2020-12-06 18:19

    This worked for me, thank you. As a caveat, although this is actually useful for my purpose, I noticed that it can also remove text content if that consists only of whitespace. For example, running the following:

    String xmlIn = "<tag> </tag> <tag>\t</tag>\t <tag>\r\n</tag><tag> text </tag>";
    String xmlOut = xmlIn.replaceAll("(?:>)(\\s*)<", "><");
    System.out.println(xmlOut);
    

    gives the following:

    <tag></tag><tag></tag><tag></tag><tag> text </tag>
    
    0 讨论(0)
  • 2020-12-06 18:25

    None of the other answers worked for me. I had to use the below code, to remove both additional whitespaces and new lines.

    xmlString.trim().replace("\n", "").replaceAll("( *)<", "<")
    
    0 讨论(0)
  • 2020-12-06 18:33

    I was able to remove whitespace/tabs/newlines from my transformation using the following property:

    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    

    You had it set to yes. I'm sure this question is old enough that it doesn't matter now; but if anyone runs into this in the future, setting the property to no saved me.

    0 讨论(0)
  • 2020-12-06 18:36

    Of course, it depends on your XML itself. However, you could try using regular expressions.

    As an example:

    yourXmlAsString.replaceAll(">[\\s\r\n]*<", "><");
    

    Would remove all whitespace between every XML element.

    0 讨论(0)
  • 2020-12-06 18:37

    Method documentBuilderFactory.setIgnoringElementContentWhitespace() controls whitespace creation. Use this before you create a DocumentBuilder.

    dbfac.setIgnoringElementContentWhitespace(true);
    
    0 讨论(0)
提交回复
热议问题