5

我有一个 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 保持以前的状态(所做的更改除外)

任何帮助将不胜感激。

提前非常感谢。

4

2 回答 2

1

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

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

看看这是否有效。

于 2014-06-06T15:08:43.317 回答
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();
        }
    }
}
于 2014-07-18T22:04:59.660 回答