[英]Add node to xml file with properties through java
I am new to XML parsing in Java I have an XML file 我是Java中XML解析的新手,我有一个XML文件
<root>
<project name="A">
<Sub name="abc">
<first property1="ab" property2="cd" property3="ed"/>
<second property1="aa" property2="dd" property3="ke"/>
</Sub>
</project>
</root>
I need to add another node as second with different property values (ie,) 我需要添加另一个具有不同属性值的节点作为第二个节点(即)
<root>
<project name="A">
<Sub name="abc">
<first property1="ab" property2="cd" property3="ed"/>
<second property1="aa" property2="dd" property3="ke"/>
<second property1="oa" property2="ld" property3="je"/>
</Sub>
</project>
</root>
Can anyone tell me how to go ahead and implement in java? 谁能告诉我如何进行Java实现?
You can do it using jdom. 您可以使用jdom来完成。 Include jdom jar in your classpath. 在您的类路径中包含jdom jar 。
Document document = (Document) new SAXBuilder().build(new File("E:/input.xml"));
Element sub = document.getRootElement().getChild("project").getChild("Sub");
Element second = new Element("second");
second.setAttribute("property1", "aa");
second.setAttribute("property2", "dd");
sub.addContent(second);
XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat().setOmitDeclaration(true));
xmlOutput.output(document, System.out);
I would follow this sequence : 我将遵循以下顺序:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.