我想使用Java在XML中追加一個屬性。例如:如何將屬性添加到Java中的現有XML元素?
<employee>
<details name="Jai" age="25"/>
<details name="kishore" age="30"/>
</employee>
它要添加weight
到它(假設它被計算並且然後響應所附)。我如何將它附加到所有項目?
<details name="Jai" age="25" weight="55"/>
我想使用Java在XML中追加一個屬性。例如:如何將屬性添加到Java中的現有XML元素?
<employee>
<details name="Jai" age="25"/>
<details name="kishore" age="30"/>
</employee>
它要添加weight
到它(假設它被計算並且然後響應所附)。我如何將它附加到所有項目?
<details name="Jai" age="25" weight="55"/>
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();
}
}
}
謝謝埃裏克它工作.. – Jeba 2010-07-22 16:55:31
你能標記我的答案接受然後呢? – 2010-07-22 23:44:43
這裏是一個快速的解決方案基於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
),接下來我們創建一個細節節點的XPath表達式,那麼我們迭代通過該表達式的元素並添加weight屬性。
最後兩行只是驗證它的白魔法:-)
謝謝Andreas_D,雖然我使用DOM進行XML解析.. – Jeba 2010-07-22 16:55:12
你已經在使用一個庫來解析這個XML並把它變成對象或數據結構? 你的問題的任何答案將取決於你已經使用的。 – 2010-07-05 18:45:25