我尝试通过引用此链接在 jdom 的帮助下更改 xml 值 - http://www.mkyong.com/java/how-to-modify-xml-file-in-java-jdom/
示例中显示的 xml:
<?xml version="1.0" encoding="UTF-8"?>
<company>
<staff id="1">
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>5000</salary>
</staff>
</company>
我不清楚如何处理以下 xml 场景:
<?xml version="1.0" encoding="UTF-8"?>
<company>
<staff>
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>
<basic>1000</basic>
<hra>150</hra>
</salary>
</staff>
<staff>
<firstname>sanjay</firstname>
<lastname>machani</lastname>
<nickname>chong</nickname>
<salary>
<basic>2000</basic>
<hra>200</hra>
</salary>
</staff>
</company>
我的员工标签不会有 id,而且我会有工资的子标签。 但是我需要使用 java 在 xml 中更改 sanjay(firstname) 的薪水。
任何建议都会有所帮助。
最佳答案
如果您使用的是 JDOM,则可以通过以下方式遍历元素:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class yourClass{
public static void main(String[] args) {
File xml = new File("yourFile.xml");
try {
Document doc = (Document) new SAXBuilder().build(xml);
Element rootNode = doc.getRootElement();
List list = rootNode.getChildren("staff");
XMLOutputter xmlOut = new XMLOutputter();
for (int i = 0; i < list.size(); i++) {
Element node = (Element) list.get(i);
if (node.getChildText("firstname").equals("sanjay"))
node.getChild("salary").getChild("basic").setText("250000");
xmlOut.setFormat(Format.getPrettyFormat());
xmlOut.output(doc, new FileWriter("yourFile.xml"));
}
} catch (IOException io) {
System.out.println(io.getMessage());
} catch (JDOMException jdomex) {
System.out.println(jdomex.getMessage());
}
}
}
关于java - 如何在 java 中使用 jdom 更改 xml 的内部节点的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13585933/