我正在尝试使用 java 创建 xml 树。
我对 JAVA 完全陌生。
我找到了一些代码。
package ep;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Tclass {
public static void main(String argv[]) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("products");
doc.appendChild(rootElement);
for(int x = 1; x < 20; x = x+1) {
// staff elements
Element staff = doc.createElement("product_id");
rootElement.appendChild(staff);
// set attribute to staff element
Attr attr = doc.createAttribute("value");
// shorten way
staff.setAttribute("value", x);
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("file.xml"));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
System.out.println("File saved!");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
}
它的工作完美。
但我尝试在它们上使用 for-loop 来创建多个元素,然后它在第 40 行返回错误我
The method setAttribute(String, String) in the type Element is not applicable for the arguments (String, int)
有什么问题?
请帮忙。
谢谢...