Форматирование файла XML: отступ - PullRequest
4 голосов
/ 31 января 2011

Я пытаюсь написать файл XML с правильным отступом. Вот мой код:

   public class WebVideo {

 private final String C_XMLFILEPATH = "resources/video.xml";
 private String itemId;
 private String videoPath;

 public WebVideo(long itemId, String videoPath) {
  this.itemId = Long.toString(itemId);
  this.videoPath = videoPath;
 }

 public void saveVideo() throws ParserConfigurationException, IOException,
   TransformerFactoryConfigurationError, TransformerException,
   SAXException {
  File xmlFile = new File(C_XMLFILEPATH);
  DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
    .newInstance();
  DocumentBuilder documentBuilder = documentBuilderFactory
    .newDocumentBuilder();
  Document document = null;
  Element rootElement = null;

  if (xmlFile.exists()) {
   document = documentBuilder.parse(xmlFile);
   rootElement = document.getDocumentElement();

  } else {
   document = documentBuilder.newDocument();
   rootElement = document.createElement("Videos");
   document.appendChild(rootElement);
  }

  Element itemElement = document.createElement("Video");
  rootElement.appendChild(itemElement);

  Element idElement = document.createElement("Id");
  Text id = document.createTextNode(itemId);
  idElement.appendChild(id);
  itemElement.appendChild(idElement);

  Element pathElement = document.createElement("Path");
  Text path = document.createTextNode(videoPath);
  pathElement.appendChild(path);
  itemElement.appendChild(pathElement);

  Transformer transformer = TransformerFactory.newInstance()
    .newTransformer();
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  transformer.setOutputProperty(
    "{http://xml.apache.org/xslt}indent-amount", "4");

  StreamResult streamResult = new StreamResult(new StringWriter());
  DOMSource domSource = new DOMSource(document);
  transformer.transform(domSource, streamResult);
  String xmlString = streamResult.getWriter().toString();

  BufferedWriter bufferedWriter = new BufferedWriter(
    new OutputStreamWriter(new FileOutputStream(xmlFile)));
  bufferedWriter.write(xmlString);
  bufferedWriter.flush();
  bufferedWriter.close();
 }
}

Все хорошо, но если вы внимательно посмотрите на выходной XML-файл, при добавлении нового элемента возникает проблема. Выходной XML-файл находится здесь:

  <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <Videos>
        <Video>
            <Id>1</Id>
            <Path>path</Path>
        </Video>
    <Video>
            <Id>2</Id>
            <Path>path</Path>
        </Video>
    </Videos>

Тег находится в том же отступе, что и тег. Как я могу решить эту проблему? Спасибо.

Ответы [ 4 ]

3 голосов
/ 31 января 2011

Проверьте этот ответ для красивой печати XML: Как правильно печатать XML из Java?

2 голосов
/ 09 марта 2012

Вы также можете создать свой собственный формат переноса строки, если вы хотите больше настроек. Добавьте текст перевода строки перед добавлением фактического дочернего элемента:

Text lineBreak = doc.createTextNode("\n\t");

element.appendChild(lineBreak);
1 голос
/ 09 мая 2016
public String formatXML(String input)
{
    try
    {
        final InputSource src = new InputSource(new StringReader(input));
        final Node document = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder().parse(src).getDocumentElement();

        final DOMImplementationRegistry registry = DOMImplementationRegistry
                .newInstance();
        final DOMImplementationLS impl = (DOMImplementationLS) registry
                .getDOMImplementation("LS");
        final LSSerializer writer = impl.createLSSerializer();

        writer.getDomConfig().setParameter("format-pretty-print",
                Boolean.TRUE);
        writer.getDomConfig().setParameter("xml-declaration", true);

        return writer.writeToString(document);
    } catch (Exception e)
    {
        e.printStackTrace();
        return input;
    }
}
1 голос
/ 31 января 2011

Некоторые библиотеки XML имеют встроенные функции печати. ​​Например, dom4j имеет OutputFormat.createPrettyPrint() - см. Руководство по его использованию на http://dom4j.sourceforge.net/dom4j-1.6.1/guide.html#Writing_a_document_to_a_file

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...