67,538
社区成员
发帖
与我相关
我的任务
分享var arrSignatures = new Array("MSXML.DOMDocument","Microsoft.XmlDom","MSXML2.DOMDocument","MSXML2.DOMDocument.3.0","MSXML2.DOMDocument.4.0","MSXML2.DOMDocument.5.0","MSXML2.DOMDocument.6.0");
var oXmlDom;
for (var i = 0; i < arrSignatures.length; i++) {
try {
oXmlDom = new ActiveXObject(arrSignatures[i]);
break;
}
catch (ex) { /* ignore */ }
}
oXmlDom.async = false;
oXmlDom.loadXML(str);
oErr = oXmlDom.parseError;
if (oErr.errorCode != 0) {
alert("解析XML数据错误:\n" + oErr.reason + "\nLine:" + oErr.line + "\nLinepos:" + oErr.linepos + "\nsrcText:\n" + oErr.srcText);
return null;
}
创建DOM,读入xml/文件,在DOM对象中对读入的内容操作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.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
class Test implements ErrorHandler {
public static void main(String args[]) {
Test test = new Test();
test.go();
}
public void go() {
Document doc = parseXmlFile("test.xml", true);
visit(doc, 0);
}
// This method visits all the nodes in a DOM tree
public static void visit(Node node, int level) {
// Process node
// If there are any children, visit each one
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
// Get child node
Node childNode = list.item(i);
if(childNode != null && childNode.getNodeType() == Node.TEXT_NODE) {
System.out.println(childNode.getTextContent());
}
// Visit child node
visit(childNode, level + 1);
}
}
// Parses an XML file and returns a DOM document.
// If validating is true, the contents is validated against the DTD
// specified in the file.
public Document parseXmlFile(String filename, boolean validating) {
try {
// Create a builder factory
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
factory.setValidating(validating);
// Create the builder and parse the file
DocumentBuilder db = factory.newDocumentBuilder();
db.setErrorHandler(this);
Document doc = db.parse(new File(filename));
return doc;
}
catch (SAXException e) {
// A parsing error occurred; the xml input is not valid
}
catch (ParserConfigurationException e) {
}
catch (IOException e) {
}
return null;
}
public void error(SAXParseException exception) throws SAXException {
// TODO Auto-generated method stub
}
public void fatalError(SAXParseException exception) throws SAXException {
// TODO Auto-generated method stub
}
public void warning(SAXParseException exception) throws SAXException {
// TODO Auto-generated method stub
}
}<books>
<book email="zhoujunhui">
<name>
<name1>rjzjh</name1>
<name2>rjzjh2</name2>
<name3>rjzjh3</name3>
</name>
<price>
<price1>jjjjjj</price1>
<price2>jjjjjj2</price2>
<price3>jjjjjj3</price3>
</price>
</book>
</books>