Я пишу файл XML, и табуляция выходит немного неправильно:Странная 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);
Любое понимание будет оценено.