如何在JAVA中使用org.w3.dom.xml在属性之间添加新行



我正在JAVA中使用org.w3c.dom和javax.xml.parsers创建xml文件。但它给我的结果如下:

<rdf:RDF xmlns:esv="http://eresources.nlb.gov.sg/ID/NLBDM/vocab-esv/" xmlns:foaf="http://xmlns.com/foaf/0.1/" xmlns:nlbdm="http://eresources.nlb.gov.sg/ID/NLBDM/vocab/" xmlns:owl="http://www.w3.org/2002/07/owl#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xmlns:xsd="http://www.w3.org/2001/XMLSchema#">
</rdf:RDF>

我需要的是将具有适当选项卡缩进的属性放在每一个属性的新行中。应该如下所示:

<rdf:RDF
    xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
    xmlns:foaf="http://xmlns.com/foaf/0.1/"
    xmlns:owl="http://www.w3.org/2002/07/owl#"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:esv="http://eresources.nlb.gov.sg/ID/NLBDM/vocab-esv/"
    xmlns:nlbdm="http://eresources.nlb.gov.sg/ID/NLBDM/vocab/">
</rdf:RDF>

我在Stackoverflow上也发现了几个相同的问题,但在回答中,他们建议更改xml解析器,我不想这么做。我可以使用现有的xml解析器做同样的事情吗?我不认为,这么小的问题他们可能没有处理好。

以下是我代码的一部分:

// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource source = new DOMSource(doc);
String tempFileName=file.getName();
tempFileName=tempFileName.substring(0,tempFileName.indexOf("."));
StreamResult result = new StreamResult(new File("C:/Users/Pratik/MapArticleURIWithNER/"+tempFileName+".rdf"));
// Output to console for testing
//StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
//System.out.println("File saved!");

我不知道有什么工具可以串行化XML,从而对结果的确切布局进行如此大的控制。你为什么在乎?额外的空白可能在视觉上很有吸引力,但任何一个正常的XML消费应用程序的行为都不会因属性之间的空白量而有所不同。

(好吧,我是这么说的,但我今天早上注意到另一个问题,那就是试图使用sed或awk处理XML。这超出了我对正常XML消费应用程序的定义…)

最新更新