Java ???? XML ????????????????????
???????????? ???????[ 2012/8/15 14:31:03 ] ????????
??????????????????????? XML ??Σ?
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="001">
<title>Harry Potter</title>
<author>J K. Rowling</author>
</book>
<book id="002">
<title>Learning XML</title>
<author>Erik T. Ray</author>
</book>
</books>
????DOM ???? XML
????Java ?е? DOM ????飺 JDK ?е? DOM API ??? W3C DOM ?淶?????? org.w3c.dom ?????? Document??DocumentType??Node??NodeList??Element ????? ??Щ????????? DOM ????????????????????????Щ????????????????? DOM ?????
????javax.xml.parsers ???е? DoumentBuilder ?? DocumentBuilderFactory ??????? XML ??????????? DOM Document ????
????javax.xml.transform.dom ?? javax.xml.transform.stream ???? DOMSource ??? StreamSource ??????????o?? DOM ???д?? XML ?????
?????????????????? DOM ???? XML ???????
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DOMParser {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
//Load and parse XML file into DOM
public Document parse(String filePath) {
Document document = null;
try {
//DOM parser instance
DocumentBuilder builder = builderFactory.newDocumentBuilder();
//parse an XML file into a DOM tree
document = builder.parse(new File(filePath));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return document;
}
public static void main(String[] args) {
DOMParser parser = new DOMParser();
Document document = parser.parse("books.xml");
//get root element
Element rootElement = document.getDocumentElement();
//traverse child elements
NodeList nodes = rootElement.getChildNodes();
for (int i=0; i < nodes.getLength(); i++)
{
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element child = (Element) node;
//process child element
}
}
NodeList nodeList = rootElement.getElementsByTagName("book");
if(nodeList != null)
{
for (int i = 0 ; i < nodeList.getLength(); i++)
{
Element element = (Element)nodeList.item(i);
String id = element.getAttribute("id");
}
}
}
}
??????
???·???
??????????????????
2023/3/23 14:23:39???д?ò??????????
2023/3/22 16:17:39????????????????????Щ??
2022/6/14 16:14:27??????????????????????????
2021/10/18 15:37:44???????????????
2021/9/17 15:19:29???·???????·
2021/9/14 15:42:25?????????????
2021/5/28 17:25:47??????APP??????????
2021/5/8 17:01:11