我需要用java管理xml。只有DOM才足够... 我需要一些非常简单或更好的东西我真的会避免安装新的库...Java中的XML解析和DOM管理
什么是在Java 6中使用的包?
我看了文档,但没有明确的规定,只是对XML的引用在组织,但没有很好的提供了...或者我没有找到它:(
谢谢
我需要用java管理xml。只有DOM才足够... 我需要一些非常简单或更好的东西我真的会避免安装新的库...Java中的XML解析和DOM管理
什么是在Java 6中使用的包?
我看了文档,但没有明确的规定,只是对XML的引用在组织,但没有很好的提供了...或者我没有找到它:(
谢谢
这是一个例子。一个完整的教程可以发现here
public class ChessboardDOMPrinter {
private DocumentBuilder builder;
public void print(String fileName, PrintStream out)
throws SAXException, IOException {
Document document = builder.parse(fileName);
NodeList nodes_i
= document.getDocumentElement().getChildNodes();
for (int i = 0; i < nodes_i.getLength(); i++) {
Node node_i = nodes_i.item(i);
if (node_i.getNodeType() == Node.ELEMENT_NODE
&& ((Element) node_i).getTagName()
.equals("CHESSBOARD")) {
Element chessboard = (Element) node_i;
NodeList nodes_j = chessboard.getChildNodes();
for (int j = 0; j < nodes_j.getLength(); j++) {
Node node_j = nodes_j.item(j);
if (node_j.getNodeType() == Node.ELEMENT_NODE) {
Element pieces = (Element) node_j;
NodeList nodes_k = pieces.getChildNodes();
for (int k = 0; k < nodes_k.getLength(); k++) {
Node node_k = nodes_k.item(k);
if (node_k.getNodeType() == Node.ELEMENT_NODE) {
Element piece = (Element) node_k;
Element position
= (Element) piece.getChildNodes().item(0);
out.println((pieces.getTagName()
.equals("WHITEPIECES")
? "White " : "Black ")
+ piece.getTagName().toLowerCase()
+ ": "
+ position.getAttribute("COLUMN")
+ position.getAttribute("ROW"));
}
}
}
}
}
}
return;
}
}
只是没有注释的代码,几乎没有一个链接不会帮助任何人... – 2011-01-24 18:14:41
的DOM API是org.w3c.dom
。要开始,你需要使用一个javax.xml.parsers.DocumentBuilder
,这可以从javax.xml.parsers.DocumentBuilderFactory
可以得到。
这一切都被默认附带的Java 6,包含在Java 6中
XML DOM解析器他re是如何使用它的片段:
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
....
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document doc = docbuilder.parse(new InputSource(reader))
使用JAXB和解析XML绑定到一个数据对象。处理数据对象很容易。 JAXB默认与java 6捆绑在一起。
E.g.
JAXBContext jc = JAXBContext.newInstance("test.schema");
Unmarshaller unmarshaller = jc.createUnmarshaller();
注 - 如果您的XML格式是固定的,那么这是个不错的选择。
你可以写一个简单的助手类来完成你的任务。看到这个http://stackoverflow.com/a/8346867/851432 – Jomoos 2011-12-01 19:15:39