我想使用Java将属性附加到XML中的现有元素。例如:
<employee>
<details name="Jai" age="25"/>
<details name="kishore" age="30"/>
</employee>
它希望向其添加weight
(假设它已计算,然后在响应中附加)。如何将其附加到所有项目?
<details name="Jai" age="25" weight="55"/>
答案 0 :(得分:3)
import org.w3c.dom.*;
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
public class AddAndPrint {
public static void main(String[] args) {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("/path/to/file.xml");
NodeList employees = document.getElementsByTagName("employee");
for (Node employee : employees) {
for (Node child : employee.getChildNodes() {
if ("details".equals(child.getNodeName()) child.setAttribute("weight", "150");
}
}
try {
Source source = new DOMSource(doc);
StringWriter stringWriter = new StringWriter();
Result result = new StreamResult(stringWriter);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(source, result);
System.out.println(stringWriter.getBuffer().toString());
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
}
答案 1 :(得分:0)
以下是基于jdom的快速解决方案:
public static void main(String[] args) throws JDOMException, IOException {
File xmlFile = new File("employee.xml");
SAXBuilder builder = new SAXBuilder();
Document build = builder.build(xmlFile);
XPath details = XPath.newInstance("//details");
List<Element> detailsNodes = details.selectNodes(build);
for (Element detailsNode:detailsNodes) {
detailsNode.setAttribute("weight", "70"); // static weight for demonstration
}
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(build, System.out);
}
首先,我们构建一个文档(SAXBuilder
),接下来我们为details节点创建一个XPath表达式,然后我们迭代该表达式的元素并添加权重属性。
最后两行只是验证它是白魔术: - )