我正在编写一个 XML 文件,并且选项卡出现了一些错误:
<BusinessEvents>
<MailEvent>
<to>Wellington</to>
<weight>10.0</weight>
<priority>air priority</priority>
<volume>10.0</volume>
<from>Christchurch</from>
<day>Mon May 20 14:30:08 NZST 2013</day>
<PPW>8.0</PPW>
<PPV>2.5</PPV>
</MailEvent>
<DiscontinueEvent>
<to>Wellington</to>
<priority>air priority</priority>
<company>Kiwi Co</company>
<from>Sydney</from>
</DiscontinueEvent>
<RoutePriceUpdateEvent>
<weightcost>3.0</weightcost>
<to>Wellington</to>
<duration>15.0</duration>
<maxweight>40.0</maxweight>
<maxvolume>20.0</maxvolume>
<priority>air priority</priority>
<company>Kiwi Co</company>
<day>Mon May 20 14:30:08 NZST 2013</day>
<frequency>3.0</frequency>
<from>Wellington</from>
<volumecost>2.0</volumecost>
</RoutePriceUpdateEvent>
<CustomerPriceUpdateEvent>
<weightcost>3.0</weightcost>
<to>Wellington</to>
<priority>air priority</priority>
<from>Sydney</from>
<volumecost>2.0</volumecost>
</CustomerPriceUpdateEvent>
</BusinessEvents>
如您所见,第一个子节点根本没有缩进,但是那个节点子节点缩进了两次?然后关闭标签只缩进一次?
我怀疑这可能与通过将根添加到文档中有关doc.appendChild(root)
,但是当我这样做时,我得到一个错误
“试图在不允许的地方插入一个节点。”
这是我的解析器:
DocumentBuilderFactory icFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder icBuilder;
try {
icBuilder = icFactory.newDocumentBuilder();
String businessEventsFile = System.getProperty("user.dir") + "/testdata/businessevents/businessevents.xml";
Document doc = icBuilder.parse (businessEventsFile);
Element root = doc.getDocumentElement();
Element element;
if(event instanceof CustomerPriceUpdateEvent){
element = doc.createElement("CustomerPriceUpdateEvent");
}
else if(event instanceof DiscontinueEvent){
element = doc.createElement("DiscontinueEvent");
}
else if(event instanceof MailEvent){
element = doc.createElement("MailEvent");
}
else if(event instanceof RoutePriceUpdateEvent){
element = doc.createElement("RoutePriceUpdateEvent");
}
else{
throw new Exception("business event isnt valid");
}
for(Map.Entry<String, String> field : event.getFields().entrySet()){
Element newElement = doc.createElement(field.getKey());
newElement.appendChild(doc.createTextNode(field.getValue()));
element.appendChild(newElement);
}
root.appendChild(element);
// output DOM XML to console
Transformer transformer = TransformerFactory.newInstance().newTransformer();
// transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "5");
DOMSource source = new DOMSource(doc);
StreamResult console = new StreamResult(businessEventsFile);
transformer.transform(source, console);
任何见解将不胜感激。