java原生读取xml
一、java原生读取xml
1.代码展示
启发 当研究mybatis的时候发现 mybatis在读取配置文件的时候 采用java原生方式
InputStream resourceAsStream2 = Thread.currentThread().getContextClassLoader().getResourceAsStream("font/test.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(false);
factory.setCoalescing(false);
factory.setExpandEntityReferences(true);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() {
@Override
public void error(SAXParseException exception) throws SAXException {
throw exception;
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
throw exception;
}
@Override
public void warning(SAXParseException exception) throws SAXException {
}
});
try {
Document document = builder.parse(resourceAsStream2);
二、方法一迭代内容
1.代码展示
"#text" 这种语法出现的原因是 原生的xml中有
public static NodeList getChildrenNode( NodeList nodeList){
for (int i = 0; i <nodeList.getLength() ; i++) {
Node item = nodeList.item(i);
if(item.getChildNodes().getLength()>1){
if(item.getNodeName()!="#text"){
getChildrenNode(item.getChildNodes()) ;
}
}else {
String nodeName = item.getNodeName();
if(nodeName!="#text"){
System.out.println(nodeName+"......."+item.getTextContent());
}
}
}
return null;
}
三、方法二迭代内容
1.代码展示
XPathFactory factory1 = XPathFactory.newInstance();
XPath xPath = factory1.newXPath();
QName NODE = new QName("http://www.w3.org/1999/XSL/Transform", "NODE");
try {
Node evaluate = (Node)xPath.evaluate("/users", document, NODE);
recursionS(evaluate);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
}
public static void recursionS(Node node) {
if(node.getChildNodes()!=null&&node.getChildNodes().getLength()>1){
NodeList childNodes = node.getChildNodes();
for (int i = 0; i <childNodes.getLength() ; i++) {
recursionS(childNodes.item(i));
}
}else{
if(node.getNodeName()!="#text")
System.out.println(node.getNodeName()+"\\\\"+node.getTextContent());
}
}