IndentingXMLStreamWriter.java的替代品

时间:2011-08-22 20:28:33

标签: java xml parsing indentation

他们是IndentingXMLStreamWriter.java的替代品我在某些时候总是遇到某种问题,虽然它在一段时间后消失但我无法编译。所以我想知道它们是否是另一种缩进手动解析的XML文件的方法

虽然当编译为netbeans模块的一部分时,错误消息略有不同......路径会被〜替换为任何想知道= p

的人
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\MasterDeckXMLImporterExporter.java:5: package com.sun.xml.internal.txw2.output does not exist
import com.sun.xml.internal.txw2.output.IndentingXMLStreamWriter;
Note: Attempting to workaround 6512707
warning: No processor claimed any of these annotations: [javax.xml.bind.annotation.XmlValue, javax.xml.bind.annotation.XmlSeeAlso, javax.xml.bind.annotation.XmlAccessorType, javax.xml.bind.annotation.XmlRootElement, javax.xml.bind.annotation.XmlAttribute]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\MasterDeckXMLImporterExporter.java:5: package com.sun.xml.internal.txw2.output does not exist
import com.sun.xml.internal.txw2.output.IndentingXMLStreamWriter;

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\MasterDeckXMLImporterExporter.java:68: cannot find symbol
symbol  : class IndentingXMLStreamWriter
location: class com.spectre.util.MasterDeckXMLImporterExporter
            xsw = new IndentingXMLStreamWriter(xsw);
2 errors
3 warnings
C:\Program Files\jmonkeyplatform\harness\suite.xml:182: The following error occurred while executing this line:
C:\Program Files\jmonkeyplatform\harness\common.xml:206: Compile failed; see the compiler error output for details.

只是要清楚一点,这将是我如何使用stax

import com.sun.xml.internal.txw2.output.IndentingXMLStreamWriter;

XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream(new File("Blah")));
xsw = new IndentingXMLStreamWriter(xsw);
xsw.writeStartDocument();
xsw.writeStartElement("map");
for (Map.Entry<String, Date> entry : map.entrySet()) {
     xsw.writeEmptyElement("entry1");
     xsw.writeAttribute("Name", entry.getKey());
     xsw.writeAttribute("date", sdf.format(entry.getValue()));
 }
 xsw.writeEndElement();
 xsw.writeEndDocument();
 xsw.close();

2 个答案:

答案 0 :(得分:1)

如果将XML解析为org.w3c.Document的实例(例如使用DocumentBuilderFactory),则可以尝试以下操作。

使用Apache Xerces:

Document doc = ...;
OutputFormat format = new OutputFormat(doc);
format.setIndenting(true);
format.setIndent(2);
XMLSerializer serializer = new XMLSerializer(out, format);
serializer.serialize(doc);

或使用标准的TransformerFactory:

Document doc = ...;
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
t.transform(new DOMSource(doc), new StreamResult(out));

答案 1 :(得分:1)

你可以使用Saxon。在s9api界面中,您可以执行类似

的操作
Processor p = new Processor();
Serializer s = p.newSerializer(System.out);
s.setOutputProperty(Property.INDENT, "yes");
XMLStreamWriter w = s.getXMLStreamWriter();

然后你有一个实现XMLStreamWriter接口的缩进序列化程序,如果你想使用它们,可以使用更多的格式化选项。