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

VTD-XMLは、空白のフォーマットを維持しながら XML ファイルの一部を変更する Java ライブラリです。

以下は、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 に答える
1

「INDENT」を有効にして、トランスフォーマーのインデント量を設定する必要があります。

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

これが機能するかどうかを確認してください。

于 2014-06-06T15:08:43.317 に答える