XML 属性中的空格

问题描述

我有一个像这样的 XML :

<document>
  <root>
    <field1>
      <a 
      Type="anyType">
        <b>Text</b>
      </a>
    <field1>
  </root>
</document>

我想删除 xml 属性 Type 和 xml 字段 a 中的空格

输出应该是这样的:

<document>
  <root>
    <field1>
      <a Type="anyType">
        <b>Text</b>
      </a>
    <field1>
  </root>
</document>

如何在 Java 中执行此操作。

编辑:生成 XML 文件代码如下:

DOMSource domSource = new DOMSource(document);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource,result);

String fileData = format(writer.toString());

// remove CR(carriage return)
fileData = fileData.replaceAll("&#[a-zA-Z0-9]{2};","");
saveDocumentIntoFile(fileData,fileName);

方法格式()

public String format(String xml) {
        
        try {
            final InputSource src = new InputSource(new StringReader(xml));
            final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
            final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml"));
            
            final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
            final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
            final LSSerializer writer = impl.createLSSerializer();
            
            // Set this to true if the output needs to be beautified.
            writer.getDomConfig().setParameter("format-pretty-print",Boolean.TRUE);
            // Set this to true if the declaration is needed to be outputted.
            writer.getDomConfig().setParameter("xml-declaration",keepDeclaration);
            
            return writer.writetoString(document);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

方法 saveDocumentIntoFile()

protected void saveDocumentIntoFile(String fileData,String fileName) throws IOException {
        FileWriter batchFile = new FileWriter(fileName);
        
        batchFile.write(fileData);
        batchFile.close();
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...