java中的XML格式 - 维护状态缩进

时间:2014-06-06 15:06:34

标签: java xml xml-formatting

我有一个XML文件,我在节点中打开并编辑了一些属性,然后将其保存回来,但由于某种原因,保存的XML没有像以前那样正确缩进。

这是我保存XML文件的代码:

    TransformerFactory transformerFactory = TransformerFactory.newInstance();       
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File(Path));
    transformer.transform(source, result); 

虽然我已指定

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

XML没有正确缩进,我希望XML状态与以前一样(除了所做的更改)

任何帮助都将非常感激。

提前多多感谢。

2 个答案:

答案 0 :(得分:1)

您需要启用'INDENT'并设置变压器的缩进量:

transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

看看这是否有效。

答案 1 :(得分:1)

VTD-XML是一个Java库,可以在保留空格格式的同时修改XML文件的各个部分。

下面是使用XPath选择XML文件中某些属性的代码。代码修改所选属性的值,然后将结果写入输出文件。

import com.ximpleware.AutoPilot;
import com.ximpleware.ModifyException;
import com.ximpleware.NavException;
import com.ximpleware.TranscodeException;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;
import com.ximpleware.XPathEvalException;
import com.ximpleware.XPathParseException;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class TransformFile
{
    public static void main(String[] args)
        throws IOException, XPathParseException, ModifyException, NavException,
        XPathEvalException, TranscodeException
    {
        String inFilename = "input.xml";
        String outFilename = "output.xml";

        transform(inFilename, outFilename);
    }

    public static void transform(String inXmlFilePath, String outXmlFilePath)
        throws XPathParseException, ModifyException, XPathEvalException,
        NavException, IOException, TranscodeException
    {
        String xpath =
            "//Configuration[starts-with(@Name, 'Release')]/Tool[@Name = 'VCCLCompilerTool']/@BrowseInformation[. = '0']";

        OutputStream fos = new FileOutputStream(outXmlFilePath);
        try {
            VTDGen vg = new VTDGen();
            vg.parseFile(inXmlFilePath, false);
            VTDNav vn = vg.getNav();
            AutoPilot ap = new AutoPilot(vn);
            ap.selectXPath(xpath);

            XMLModifier xm = new XMLModifier(vn);

            int attrNodeIndex;
            while ((attrNodeIndex = ap.evalXPath()) != -1) {
                // An attribute value node always immediately follows an
                // attribute node.
                int attrValIndex = attrNodeIndex + 1;
                xm.updateToken(attrValIndex, "1");
            }

            xm.output(fos);
        }
        finally {
            fos.close();
        }
    }
}